强制读取多个字节以获取 Uvarint。

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

Force go to read multiple bytes for a Uvarint

问题

假设我有以下的两个字节数组,这些数组是我从文件中读取的:

bits := []byte{3, 223}

我想将它们解释为一个整数,即991(第一个数字是0b11,第二个数字是0b11011111)。我尝试使用Go语言来实现这个目标,但遇到了困难。

import "encoding/binary"
import "fmt"

bits := []byte{3, 223}
fmt.Println(binary.Uvarint(bits))

这段代码只读取了"3",然后停止了。使用binary.Read等方法也会出现类似的问题。

我相信我在这里漏掉了一些惯用法,希望你能帮助我。

谢谢,Kevin

英文:

Lets say I have the following 2 byte array, that I've read from a file.

bits := []byte{3, 223}

I would like to interpret this as one integer, which would be 991 (0b11 from the first number, 0b11011111 from the second). I'm trying to do this with Go and running into difficulty.

import "encoding/binary"
import "fmt"

bits := []byte{3, 223}
fmt.Println(binary.Uvarint(bits))

This reads the "3" and then stops. Similarly for binary.Read... etc.

I'm sure there is some idiom that I am missing here, and would appreciate your help.

Thanks, Kevin

答案1

得分: 4

啊,我需要使用ByteOrder构造函数

import "encoding/binary"
import "fmt"

bits := []byte{3, 223}
fmt.Println(binary.BigEndian.Uint16(bits))
英文:

Ah, I needed to use the ByteOrder constructor

import "encoding/binary"
import "fmt"

bits := []byte{3, 223}
fmt.Println(binary.BigEndian.Uint16(bits))

huangapple
  • 本文由 发表于 2014年4月29日 21:45:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/23366482.html
匿名

发表评论

匿名网友

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

确定