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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?