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

如何在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 :)

图片转代码服务由CSDN问答提供 功能建议

我想将byte []变量的asic值添加到整数中。 例如,我先读一个byte []缓冲区中的所有输入。 然后我得到一个数字字符串“ 123”。 然后我可以通过('1'-'0')* 100 +('2'-'0')* 10 +'3'-'0'将其分配给一个整数。 但是我不能给整数赋字节变量。 我怎样才能做到这一点? 非常感谢:)

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    打赏 评论
  • douren9077 2016-09-12 16:27

    If you need to read an integer from a stream of bytes, the fastest way would be just to scan it with fmt. Example:

    n := 0
    _, err := fmt.Scanf("%d", &n)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("you entered %d
    ", n)
    
    打赏 评论

相关推荐 更多相似问题