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

huangapple go评论114阅读模式
英文:

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

问题

你可以使用encoding/binary包中的PutVarint函数将int64类型转换为[]byte类型。这个函数可以处理正数和负数,不会破坏负数的表示。以下是一个示例代码:

import (
    "encoding/binary"
    "fmt"
)

func main() {
    id := int64(-1234567890)
    buf := make([]byte, binary.MaxVarintLen64)
    n := binary.PutVarint(buf, id)
    result := buf[:n]
    fmt.Println(result)
}

在这个示例中,我们将int64类型的id转换为[]byte类型的buf,然后使用PutVarint函数将id写入buf中。最后,我们将buf切片为实际写入的部分,并打印结果。

请注意,PutVarint函数返回写入的字节数,你可以根据需要使用切片操作截取实际写入的部分。

英文:

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.

答案1

得分: 96

int64uint64之间进行转换不会改变符号位,只会改变其解释方式。

你可以使用正确的ByteOrder来使用Uint64PutUint64函数。

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)

输出结果:

-123456789
[235 50 164 248 255 255 255 255]
-123456789
英文:

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

答案2

得分: 8

你可以使用以下代码:

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
英文:

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

答案3

得分: 7

如果您不关心符号或字节顺序(例如,用于哈希映射键等原因),您可以简单地进行位移操作,然后与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的字节切片)

英文:

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)

答案4

得分: 5

代码:

var num int64 = -123456789

// 将 int64 转换为 []byte
buf := make([]byte, binary.MaxVarintLen64)
n := binary.PutVarint(buf, num)
b := buf[:n]

// 将 []byte 转换为 int64
x, n := binary.Varint(b)
fmt.Printf("x 的值为:%v,n 的值为:%v\n", x, n)

输出结果:

x 的值为:-123456789,n 的值为:4
英文:

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

outputs

x is: -123456789, n is: 4

答案5

得分: 3

如果你需要在Go语言中实现类似于int.to_bytes(length, byteorder, *, signed=False)的功能,你可以这样做:

func uint64ToLenBytes(v uint64, l int) (b []byte) {
	b = make([]byte, l)

	for i := 0; i < l; i++ {
		f := 8 * i
		b[i] = byte(v >> f)
	}

	return
}

func int64ToLenBytes(v int64, l int) (b []byte) {
	return uint64ToLenBytes(uint64(v), l)
}

它将返回一个字节切片,例如:

ba := int64ToLenBytes(258, 3)
fmt.Printf("%#v\n", ba)

// 输出:
[]byte{0x2, 0x1, 0x0}
英文:

If you need a similar function as int.to_bytes(length, byteorder, *, signed=False) in Go you can do this:

func uint64ToLenBytes(v uint64, l int) (b []byte) {
	b = make([]byte, l)

	for i := 0; i &lt; l; i++ {
		f := 8 * i
		b[i] = byte(v &gt;&gt; f)
	}

	return
}

func int64ToLenBytes(v int64, l int) (b []byte) {
	return uint64ToLenBytes(uint64(v), l)
}

It will return a slice of bytes, for example:

ba = int64ToLenBytes(258, 3)
fmt.Printf(&quot;%#v\n&quot;, ba)

// output:
[]byte{0x2, 0x1, 0x0}

答案6

得分: 2

这是一个简单的函数,可以实现你想要的功能:

func Int64ToBytes(number int64) []byte {
	big := new(big.Int)
	big.SetInt64(number)
	return big.Bytes()
}
英文:

Here's a simple function that should accomplish what you are wanting:

func Int64ToBytes(number int64) []byte {
	big := new(big.Int)
	big.SetInt64(number)
	return big.Bytes()
}

huangapple
  • 本文由 发表于 2016年2月13日 04:11:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/35371385.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定