The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
mzmxcvbn

golang 里关于 string 和[]byte 的一个小问题

  •  
  •   mzmxcvbn · Dec 28, 2018 · 4438 views
    This topic created in 2732 days ago, the information mentioned may be changed or developed.

    刚开始学 Go 现在有 s = "4e722e3137"的字符串。
    我想把 s 转成 []byte{0x4e, 0x72, 0x2e, 0x31, 0x37} 这样的形式,也就是[78 114 46 49 55],也就是字符串里的每两个字符表示成 1 个字节。
    但直接[]byte("4e722e3137")出来的是[52 101 55 50 50 101 51 49 51 55]。

    我现在用这样的方法能勉强达到要求:

    baseData = []byte("4e722e3137")
    var res []byte
    for i:=0; i<=len(baseData); i=i+2 {
        raw := string(baseData[i:i+2])
        i, _ := strconv.ParseInt(raw, 16, 8)
        res = append(res, byte(i))
    }
    

    但感觉这样确实很蠢,而且性能也不佳,我想问一下有没有更好的方法能转成我需要的格式

    6 replies    2018-12-28 15:01:23 +08:00
    xj577
        1
    xj577  
       Dec 28, 2018
    hex.DecodeString("4e722e3137")
    anying
        3
    anying  
       Dec 28, 2018
    data, err := hex.DecodeString("4e722e3137")
    coyove
        4
    coyove  
       Dec 28, 2018
    以 go 的设计理念来说你的写法没什么不对的,记得检查一下 ParseInt 返回的 err
    maichael
        5
    maichael  
       Dec 28, 2018
    同上,用 hex.DecodeString
    mzmxcvbn
        6
    mzmxcvbn  
    OP
       Dec 28, 2018
    解决了,谢谢楼上的各位
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5930 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 99ms · UTC 02:20 · PVG 10:20 · LAX 19:20 · JFK 22:20
    ♥ Do have faith in what you're doing.