質問

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())
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top