package main
import (
"encoding/binary"
"fmt"
"bytes"
)
func main(){
b := new(bytes.Buffer)
c := new(bytes.Buffer)
binary.Write(b, binary.LittleEndian, []byte{0, 1})
binary.Write(b, binary.BigEndian, []byte{0, 1})
binary.Write(c, binary.LittleEndian, uint16(256))
binary.Write(c, binary.BigEndian, uint16(256))
fmt.Println(b.Bytes()) // [0 1 0 1]
fmt.Println(c.Bytes()) // [0 1 1 0]
}
It is very interesting, why binary.Write()
byte ordering is working for uint8, uint16, uint64
..etc, but []byte
?
If []byte
need to be ordered by binary.LittleEndian
and write to bytes.Buffer
, it needs to be reversed first? Is there any effective ways to solve this problem?
Thanks.
Only integer types get swapped by byte ordering.
When it's a slice of bytes, the binary package wouldn't really know what to swap.
For example, how would it know what to do if you passed 1k of data?
Treat it as int16, int32 or int64?
Or would you expect it to just reverse the whole slice?
Because there is nothing to order by. A byte is 8 bits, so you can go (unsigned) from 0 to 255. ie. uint16
you have 2 bytes, so you can order them differently.
ByteOrder
is not even defined for int8
. You can check the source code to see that binary.Write
simply not uses the passed order when types are uint8
or int8
. (A byte
is an alias to uint8
)