Reputation: 64774
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?
Upvotes: 2
Views: 1827
Reputation: 64774
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())
Upvotes: 1