douci6541 2016-09-12 16:15
浏览 335
已采纳

如何在golang中将字节的ASCII值添加到整数?

I'd like to get a byte[] variables' asic value added to an integer. For example, I fisrt read all input in a byte[] buffer. And then I get out a number string "123" in it. And then I can assign it to an integer by ('1' - '0')*100 + ('2' - '0')*10 + '3' - '0'. But I can not assign integers with byte variables. How can I do that with any means? Thank you very much :)

  • 写回答

2条回答 默认 最新

  • duanba7498 2016-09-12 18:02
    关注

    In go, you can convert byte array to string with the string() coercion and then use strconv.Atoi on it. Presumably, you also want to use slice operations to isolate just the part of the input you want to convert.

    package main
    
    import (
        "strconv"
        "fmt"
    )
    
    func main() {
        data := []byte { 0x20, 0x31, 0x32, 0x33, 0x20 } // Embedded number
        // string(...) coercion yields a string from a byte buffer
        // Number starts at char 1, ends before char 4
        str := string(data[1:4])
        i, err := strconv.Atoi(str)
        if err != nil {
            fmt.Printf("Error %v
    ", err)
            return
        }
    
        fmt.Printf("value %v
    ", i)
    }
    

    Prints

    value 123
    

    And since go has nicely hygenic practicies, errors will be handled too.

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

报告相同问题?

悬赏问题

  • ¥15 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!