How to transfer hex strings to []byte directly in Go?

24,600

Simply use the hex.DecodeString() function:

s := "46447381"

data, err := hex.DecodeString(s)
if err != nil {
    panic(err)
}
fmt.Printf("% x", data)

Output:

46 44 73 81

Try it on the Go Playground.

Note:

If you just simply print the byte slice using fmt.Println(data), the printed values will be in decimal format that's why it won't match your input string (because it is specified in hexadecimal format).
Output of fmt.Println(data) would be:

[70 68 115 129]

These are the same numbers just in decimal base.

Share:
24,600

Related videos on Youtube

cuuboy
Author by

cuuboy

Updated on July 25, 2020

Comments

  • cuuboy
    cuuboy almost 4 years

    Question is simple,

    how to transfer "46447381" in to []byte{0x46,0x44,0x73,0x81}?

    • cuuboy
      cuuboy about 9 years
      That would be more complicated than I thought, because I just use hex.EncodeToString, I wonder why I cannot use kind of this function to let it back.
    • cuuboy
      cuuboy about 9 years
      @EdmDroid yes question is simple, but that means I want a simple answer.
  • cuuboy
    cuuboy about 9 years
    You're right, I'm so stupid, I thought that should not be transferred into dec, but indeed it should be, thanks. play.golang.org/p/S_blDzfpN7