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