Question is simple,
how to transfer "46447381"
in to []byte{0x46,0x44,0x73,0x81}
?
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);
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With