Question

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?

Was it helpful?

Solution

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())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top