类型转换
[]byte and string:
// string to byte
var str string = "hello world."
b := []byte(str)
// byte to string
s := string(b)
// 前 n 个字节转成string
s := string(b[:n])
number and string
import "strconv"
// int64 to string
var num int64 = 76672067
var base int = 10 // 10进制, (0, 2 - 36)
curPosStr := strconv.FormatInt(num, base)
// string to int64
var line string = "76672067"
var base int = 10 // 10进制, (0, 2 - 36)
var bitSize int = 64 // int位数, (0 - 64)
numInt64, err := strconv.ParseInt(line, base, bitSize)
if err != nil {
fmt.Println(err)
}
number and []byte
import "bytes"
import "encoding/binary"
// int64 to byte
var num int64 = 76672067
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, num)
numByte := bytesBuffer.Bytes()
// byte to int64
b := []byte("76672067")
bytesBuffer := bytes.NewBuffer(b)
var x int64
binary.Read(bytesBuffer, binary.BigEndian, &x)