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?
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?
收起
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())
报告相同问题?