encoding/hex: invalid byte: U+0068 'h' Golang

10,971

Solution 1

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)

Solution 2

Your code is trying to decode from hex. That string is not hex encoded.

To encode to hex try this

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

fmt.Printf("Decoded bytes %v", []byte(b))
Share:
10,971
Karthic Rao
Author by

Karthic Rao

Updated on June 04, 2022

Comments

  • Karthic Rao
    Karthic Rao almost 2 years

    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 \n ", 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].