dongyulian5801 2017-10-30 13:09
浏览 91
已采纳

尝试在Golang中将字节片解析为基数16

I'm trying to parse a slice of bytes with the below value 020000 to as a base 16 number but haven't gotten it working yet. What am I doing wrong?

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)
}

https://play.golang.org/p/eM5RQAJdoL

  • 写回答

2条回答 默认 最新

  • dongshang4984 2017-10-30 13:33
    关注

    You've got a raw byte slice that is the bytes making up the number you want, but you're instead parsing it as if it were the bytes making up the string representation of the bytes making up the number you want. Rather than attempting to parse as a string, parse as what it is - bytes. You can do this using the binary package, which, per its documentation:

    implements simple translation between numbers and byte sequences and encoding and decoding of varints.

    Which is exactly what you want. How you use it will depend on the endianness and encoding of the data, but the documentation should get you going in the right direction.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 CATIA有些零件打开直接单机确定终止
  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址