从Golang中的读取器中读取小于8位的数据。

huangapple go评论83阅读模式
英文:

Reading < 8 bits from a reader in Golang

问题

在处理 Golang 中的原始 IP 数据包时,我遇到了一个问题,似乎找不到解决办法:

IPv4 规范 中包含了比 8 位小的字段。例如,版本或头部长度(每个字段占 4 位)或标志位(3 位)。

我该如何从 io.Reader 中读取这些值,并在 Golang 中进行处理?到目前为止,我一直在使用 binary.Read 方法,但由于 Golang 中最小的整数类型是 int8,所以在这种情况下不可能使用该方法。

英文:

While handling raw IP packages in Golang I've came across a problem which I cannot seem to find a solution for:

The IPv4 specification contains fields which are smaller than 8 bits. For example the Version or the Header Length (4 bits each) or the Flags (3 bits).

How do I read those values from an io.Reader and handle them using Golang afterwards? I've been using the binary.Read method so far, however since the smallest integer type in Golang is an int8, that is not possible in this case.

答案1

得分: 15

io.Reader只能读取字节,而不能读取位。你可以读取字节并自己提取位:

var (
    byte0 byte = 0xAF
    byte5 byte = 0x89
)

version := byte0 >> 4
headerLength := byte0 & 0x0F
flags := byte5 >> 5

当然,另一种方法是编写一个BitReader类型,这可能更高效,但你可以理解这个思路:http://play.golang.org/p/Wyr_K9YAro 从Golang中的读取器中读取小于8位的数据。

英文:

io.Reader can only read bytes, not bits. What you can do is read the bytes and extract the bits yourself:

var (
    byte0 byte = 0xAF
    byte5 byte = 0x89
)

version := byte0 &gt;&gt; 4
headerLength := byte0 &amp; 0x0F
flags := byte5 &gt;&gt; 5

Of course, another approach is to write a BitReader type, which could of course be more efficient but you get the idea: http://play.golang.org/p/Wyr_K9YAro 从Golang中的读取器中读取小于8位的数据。

huangapple
  • 本文由 发表于 2015年4月12日 05:05:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/29583024.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定