golang Endian字节序

只谈情不闲聊 提交于 2019-12-06 02:51:50

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{}) error
func Write(w io.Writer, order ByteOrder, data interface{}) error

及一个排序接口

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 因为序列不一样,值按照小端序得来。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!