Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Question is simple,

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

like image 611
cuuboy Avatar asked Feb 09 '15 06:02

cuuboy


People also ask

How do you convert a hex string to a byte array?

To obtain a string in hexadecimal format from this array, we simply need to call the ToString method on the BitConverter class. As input we need to pass our byte array and, as output, we get the hexadecimal string representing it. string hexString = BitConverter. ToString(byteArray);

Is hex a 1 byte?

Now, let's convert a hexadecimal digit to byte. As we know, a byte contains 8 bits. Therefore, we need two hexadecimal digits to create one byte.

How do I create a byte array in Golang?

To create a byte in Go, assign an ASCII character to a variable. A byte in Golang is an unsigned 8-bit integer. The byte type represents ASCII characters, while the rune data type represents a broader set of Unicode characters encoded in UTF-8 format.


1 Answers

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.

like image 192
icza Avatar answered Nov 15 '22 13:11

icza