最近看TCP通讯发现字节序,对此不太了解,故记录下来。golang
所谓字节序就是字符顺序。在查看资料经常使用的有2类排序方式:ui
Big-Endian编码
高位字节放在内存的低地址端,低位字节放在内存的高地址端。code
Little-Endian排序
低位字节放在内存的低地址段,高位字节放在内存的高地址端。接口
十进制数255
用二进制表示为1111 1111
,十进制数256
用二进制表示则为1 0000 0000
那么这个1存放的位置是在前仍是后,就是 Big-Endian 和 ittle-Endian 的区别内存
在golang 中 encoding/binary
提供了二进制序列化的功能。string
提供read 读取编码 和write写编码的等方法it
func Read(r io.Reader, order ByteOrder, data interface{}) error func Write(w io.Writer, order ByteOrder, data interface{}) error
及一个排序接口io
type ByteOrder interface { Uint16([]byte) uint16 Uint32([]byte) uint32 Uint64([]byte) uint64 PutUint16([]byte, uint16) PutUint32([]byte, uint32) PutUint64([]byte, uint64) String() string } type littleEndian struct{} type bigEndian struct{}
bigEndian和littleEndian实现了接口方法。
利用 Write 进行编码获得以下结果:
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]
利用read去读 编码中的数据:
ioTest := bytes.NewBuffer(make([]byte,0,1024)) binary.Write(ioTest,binary.BigEndian,uint32(10)) ioLen :=uint32(0) binary.Read(ioTest,binary.BigEndian,&ioLen) fmt.Println(ioLen) // 10 ioLen :=uint32(0) binary.Read(ioTest,binary.LittleEndian,&ioLen) fmt.Println(ioLen) // 167772160 由于序列不同,值按照小端序得来。