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])
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路