dongqi4085 2019-05-16 12:31 采纳率: 0%
浏览 221
已采纳

将十六进制值的字符串转换为[] byte表示形式

I have seen multiple questions to convert String to byte array, but what I want is to cast to byte[]. So that for instance, if I have a := "68656c6c6f20776f726c64", if I do []byte(a), it will convert each number into its hex value, but what I want is that it is directly interpreted as hex directly, so that I have []byte b = [68, 65, 6c, etc.]

Is there any other way different to iterating the string and every 2 characters appending them to the []byte?

  • 写回答

1条回答 默认 最新

  • doushi4956 2019-05-16 12:58
    关注

    A string is a byte array. Casting one to the other gets what you're seeing; the character a has an integer value (97, or 61 in hexadecimal), and you're getting the byte array that makes up the string of characters. If you want the string "ff" to become the integer 255 (ff in hexadecimal), that's not casting, that's parsing (decoding) the string based on a particular logic (i.e. that the string is made up of ASCII representations of hexadecimal digits). To do that you want to use an appropriate decoder, i.e. the standard library's hex.DecodeString as mh-cbon suggested:

    src := []byte("68656c6c6f20776f726c64")
    
    dst := make([]byte, hex.DecodedLen(len(src)))
    n, err := hex.Decode(dst, src)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("%s
    ", dst[:n])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口