dongwei7048
2016-02-12 20:11
浏览 454
已采纳

如何在go中将int64转换为字节数组?

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.

图片转代码服务由CSDN问答提供 功能建议

我有一个用 int64 表示的ID。 如何将其转换为 [] byte ? 我看到二进制包为uint做到了这一点,但我想确保我不会破坏负数。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • dousong5161 2016-02-12 20:37
    已采纳

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

    You can use Uint64 and PutUint64 with the correct ByteOrder

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

    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)
    

    output:

    -123456789
    [235 50 164 248 255 255 255 255]
    -123456789
    
    已采纳该答案
    打赏 评论
  • dq_609586475 2017-12-26 12:17

    The code:

    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
    ", x, n)
    

    outputs

    x is: -123456789, n is: 4
    
    打赏 评论
  • douxiezha9319 2018-08-11 23:02

    You can use this too:

    var num int64 = -123456789
    
    b := []byte(strconv.FormatInt(num, 10))
    
    fmt.Printf("num is: %v, in string is: %s", b, string(b))
    

    Output:

    num is: [45 49 50 51 52 53 54 55 56 57], in string is: -123456789
    
    打赏 评论
  • duanbichenhe1968 2019-07-30 05:34

    If you don't care about the sign or endianness (for example, reasons like hashing keys for maps etc), you can simply shift bits, then AND them with 0b11111111 (0xFF):

    (assume v is an int32)

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

    (for int64/uint64, you'd need to have a byte slice of length 8)

    打赏 评论

相关推荐 更多相似问题