This is a creation in Article, where the information may have evolved or changed.
Golang byte order
Briefly
The recent discovery of the byte order in TCP communication is not well understood and therefore recorded.
The so-called byte order is the character sequence. There are 2 types of sorting methods commonly used in viewing data:
Big-endian
The high bit byte is placed at the low address end of the memory, and the low byte is placed on the upper address side of the memory.
Little-endian
The lower byte is placed in the low address segment of the memory, and the high byte is placed on the upper address side of the memory.
For example
The decimal number is represented by a binary notation 255
1111 1111
, and the decimal number is represented by a binary notation. 256
1 0000 0000
So the position of this 1 is before or after, that is the difference between Big-endian and Ittle-endian.
In Golang
The functionality of binary encoding/binary
serialization is provided in Golang.
Provide read read and write encoding methods
func Read(r io.Reader, order ByteOrder, data interface{}) errorfunc Write(w io.Writer, order ByteOrder, data interface{}) error
and a sort interface
type ByteOrder interface {Uint16([]byte) uint16Uint32([]byte) uint32Uint64([]byte) uint64PutUint16([]byte, uint16)PutUint32([]byte, uint32)PutUint64([]byte, uint64)String() string}type littleEndian struct{}type bigEndian struct{}
Bigendian and Littleendian implement the interface method.
For example
The following results are obtained by using Write encoding:
ioTest := bytes.NewBuffer(make([]byte,0,1024))binary.Write(ioTest,binary.LittleEndian,uint32(10))fmt.Println(ioTest.Next(4)) // [10 0 0 0]binary.Write(ioTest,binary.BigEndian,uint32(10))fmt.Println(ioTest.Next(4) // [0 0 0 10]
Use read to read the data in the encoding:
iotest: = bytes. Newbuffer (Make ([]byte,0,1024)) binary. Write (iotest,binary. Bigendian,uint32 (Ten)) Iolen: =uint32 (0) binary. Read (iotest,binary. Bigendian,&iolen) fmt. PRINTLN (Iolen)//10ioLen: =uint32 (0) binary. Read (iotest,binary. Littleendian,&iolen) fmt. PRINTLN (Iolen)//167772160 because the sequence is different, the value is derived in small order.