我正在尝试将具有以下值 020000
的 byte slice 段解析为以 16 为基数的数字,但尚未使其正常工作。我做错了什么?
package main
import (
"fmt"
"strconv"
)
func main() {
input := []byte{0, 2, 0, 0, 0, 0}
expectation := 131072
actual := headerVersion(input)
if actual != expectation {
panic(fmt.Sprintf("Expected %v but got %v.", expectation, actual))
}
}
func headerVersion(input []byte) int {
output, _ := strconv.ParseUint(string(input), 16, 64)
return int(output)
}
最佳答案
你有一个原始字节 slice ,它是组成你想要的数字的字节,但你将它解析为好像它是组成你想要的数字的字节的字符串表示的字节。与其尝试解析为字符串,不如解析为字节。您可以使用 binary
package 执行此操作,根据其文档:
implements simple translation between numbers and byte sequences and encoding and decoding of varints.
这正是您想要的。您如何使用它取决于数据的字节序和编码,但文档应该让您朝着正确的方向前进。
关于string - 尝试将 byte slice 解析为 Golang 中的 16 进制数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47016103/