golang Endian位元組序

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

golang 位元組序

簡述

最近看TCP通訊發現位元組序,對此不太瞭解,故記錄下來。

所謂位元組序就是字元順序。在查看資料常用的有2類排序方式:

  • Big-Endian

    高位位元組放在記憶體的低地址端,低位位元組放在記憶體的高地址端。

  • Little-Endian

    低位位元組放在記憶體的低位址區段,高位位元組放在記憶體的高地址端。

例如

十進位數255用二進位表示為1111 1111,十進位數256用二進位表示則為1 0000 0000那麼這個1存放的位置是在前還是後,就是 Big-Endian 和 ittle-Endian 的區別

golang中

在golang 中 encoding/binary 提供了二進位序列化的功能。

提供read 讀取編碼 和write寫編碼的等方法

func Read(r io.Reader, order ByteOrder, data interface{}) errorfunc Write(w io.Writer, order ByteOrder, data interface{}) error

及一個排序介面

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和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)  // 10ioLen :=uint32(0)binary.Read(ioTest,binary.LittleEndian,&ioLen)fmt.Println(ioLen)  // 167772160 因為序列不一樣,值按照小端序得來。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.