How can I convert an int64 into a byte array in go?

时间:2016-02-12 20:11:02

标签: go casting

I have an id that is represented at an int64. How can I convert this to a []byte? I see that the binary package does this for uints, but I want to make sure I don't break negative numbers.

5 个答案:

答案 0 :(得分:43)

Converting between inline-block and int64 doesn't change the sign bit, only the way it's interpreted.

You can use uint64 and Uint64 with the correct ByteOrder

http://play.golang.org/p/wN3ZlB40wH

PutUint64

output:

i := int64(-123456789)

fmt.Println(i)

b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, uint64(i))

fmt.Println(b)

i = int64(binary.LittleEndian.Uint64(b))
fmt.Println(i)

答案 1 :(得分:3)

如果您不关心符号或字节序(例如,诸如地图的哈希键之类的原因),则只需移位位,然后将它们与0b11111111(0xFF)进行“与”操作即可:

(假设v是int32)

b := [4]byte{
        byte(0xff & v),
        byte(0xff & (v >> 8)),
        byte(0xff & (v >> 16)),
        byte(0xff & (v >> 24))}

(对于int64 / uint64,您需要一个长度为8的字节片)

答案 2 :(得分:2)

代码:

var num int64 = -123456789

// convert int64 to []byte
buf := make([]byte, binary.MaxVarintLen64)
n := binary.PutVarint(buf, num)
b := buf[:n]

// convert []byte to int64
x, n := binary.Varint(b)
fmt.Printf("x is: %v, n is: %v\n", x, n)

输出

x is: -123456789, n is: 4

答案 3 :(得分:1)

"encoding/binary" 库中,您可以使用方法 PutVariant([]byte,int64) 从 int64 传输到字节,使用 Variant([]byte) 从字节传输到 int64,无需任何进一步的转换。 Go playgruond

中的此代码
buf := make([]byte, 8)

var toBytes int64 = 900
fmt.Printf("toBytes:%d\n", toBytes)

binary.PutVarint(buf, toBytes)
fmt.Printf("buffer:%v\n", buf[:])

fromBytes, _ := binary.Varint(buf)
fmt.Printf("fromBytes:%d\n", fromBytes)

答案 4 :(得分:0)

您也可以使用它:

var num int64 = -123456789

b := []byte(strconv.FormatInt(num, 10))

fmt.Printf("num is: %v, in string is: %s", b, string(b))

输出:

num is: [45 49 50 51 52 53 54 55 56 57], in string is: -123456789