最近看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 由於序列不同,值按照小端序得來。