dpyu7978 2015-03-31 03:41
浏览 2128
已采纳

编码/十六进制:无效字节:U + 0068'h'Golang

I'm trying to convert a string into a byte array containing its hexadecimal values, here is the code I've written:

package main

import (
     "encoding/hex"
     "fmt"
     "os"
)

func main() {
     str :="abcdefhijklmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ123456789"

     b, err := hex.DecodeString(str)

     if err != nil {
             fmt.Println(err)
             os.Exit(1)
     }

     fmt.Printf("Decoded bytes %v 
 ", b)
}

Here is the link from Go PlayGround: http://play.golang.org/p/8PMEFTCYSd

But it's giving me the error *encoding/hex: invalid byte: U+0068 'h' Golang *. What's the problem here? I want to convert my string into byte array containing hexadecimal values of each character in the string. I want b[n] to contain hexadecimal value of str[n].

  • 写回答

2条回答 默认 最新

  • douwen5546 2015-03-31 07:14
    关注

    I want to convert my string into byte array containing hexadecimal values of each character in the string.

    You can simply convert a string to a []byte (byte slice, not exactly the same as array!) by using a simple type conversion:

    b := []byte(str)
    

    And you're done!

    If you want to print it as a hexadecimal string, you can do that with the fmt.Printf() function using both the string and the []byte:

    fmt.Printf("%x", str)
    // Or:
    fmt.Printf("%x", b)
    

    Tip: you can use the format string "% x" to have a space printed between each of the hexadecimal forms of the bytes/characters:

    fmt.Printf("% x", str)
    

    If you want the result of the hexadecimal form as a string, you can use the fmt.Sprintf() variant:

    hexst := fmt.Sprintf("%x", str)
    // Or:
    hexst := fmt.Sprintf("%x", b)
    

    Or as an alternative you can use the hex.EncodeToString() function from the encoding/hex package:

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

报告相同问题?

悬赏问题

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