英文:
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
英文:
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 >> 4
headerLength := byte0 & 0x0F
flags := byte5 >> 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论