drdawt9210 2014-12-04 06:42
浏览 485
已采纳

使用GO语言将ASCII数字字符的字节数组转换为int

I see some answers to exactly the same question I have: How to convert Byte array to int in GO programming language?

I wrote below function to convert byte array to int

func convertByteToInt(in []byte) int32 {
    return  (int32(in[0]) << 24 | int32(in[1]) << 16 | int32(in[2]) << 8 | int32(in[3]))
}

Before that, I made sure that byte array has correct(base 256) values. in[0] = 54 (ASCII for 6), in[1] = 54 (ASCII for 6), in[2] = 49 (ASCII for 1), in[3] = 49 (ASCII for 1).

So I am expecting to retrieve integer 6611 value from byte array, but I ended up getting 909521201. I fail to understand what is exactly going on in such a simple conversion. Can anyone flash some light?

THanks

  • 写回答

4条回答 默认 最新

  • drema2014 2014-12-04 11:12
    关注

    @Volker is right in his comment, you don't have a binary number in your array, you have an ASCII string. Yet, you try to decode it as binary. Note there's no need to validate any input (maybe except the length) if you were dealing with binary number, as all single byte values are valid.

    @Ainar-G gave you a way of converting ASCII number into integer.

    Compare these two approaches: (http://play.golang.org/p/_wufZ4P_aE)

    buf := []byte{54, 54, 49, 49}
    
    x, _ := strconv.Atoi(string(buf))
    fmt.Println(x)
    

    This prints 6611; but look at this:

    var y int32
    _ = binary.Read(bytes.NewReader(buf), binary.BigEndian, &y)
    fmt.Println(y)
    

    This prints 909521201, so exactly what you got (and didn't expect). As a side note, you're manually decoding it as BigEndian, so this is not "such a simple conversion" at the end, because there're some more factors to consider.

    Your handcrafted conversion from ASCII would look more or less as follows:

    var x int32
    for _, c := range in {
        x = x*10 + int32(c - '0')
    }
    return x
    

    But using strconv is the way to go.

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

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况