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条)

报告相同问题?

悬赏问题

  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败