How would I write a 16-bit integer to multiple bytes in Golang?

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

How would I write a 16-bit integer to multiple bytes in Golang?

问题

让我们假设我有一个16位整数259(二进制为0000000100000011),我想要将它写入Go语言的字节流中。一个字节只有8位,那么我该如何将整数分割成多个字节?

英文:

Let's say I have the 16 bit integer 259 (0000000100000011 in binary) and I want to write it to a byte stream in Go. A byte is only 8 bits, so how can I split the integer across multiple bytes?

答案1

得分: 1

使用encoding/binary包的binary.Write方法。

buf := new(bytes.Buffer)
err := binary.Write(buf, binary.BigEndian, uint16(259))
if err != nil {
    fmt.Println("binary.Write failed:", err)
}

// 这应该是两个字节的编码整数。
fmt.Println(buf.Bytes())

请注意,binary.Write方法将一个值以指定的字节顺序写入到给定的缓冲区中。在上述示例中,我们使用binary.BigEndian作为字节顺序,并将uint16(259)写入到buf中。最后,我们通过buf.Bytes()方法获取编码后的整数的字节表示形式。

英文:

Use the binary.Write method of the encoding/binary package.

buf := new(bytes.Buffer)
err := binary.Write(buf, binary.BigEndian, uint16(259))
if err != nil {
	fmt.Println("binary.Write failed:", err)
}

// This should be two bytes with your encoded integer.
fmt.Println(buf.Bytes())

huangapple
  • 本文由 发表于 2014年5月6日 13:27:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/23486579.html
匿名

发表评论

匿名网友

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

确定