To convert byte array to a hex value, we loop through each byte in the array and use String 's format() . We use %02X to print two places ( 02 ) of Hexadecimal ( X ) value and store it in the string st .
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);
Hexadecimal is used in the transfer encoding Base16, in which each byte of the plaintext is broken into two 4-bit values and represented by two hexadecimal digits.
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.
If I understood correctly you want to return the %x format:
you can import hex and use the EncodeToString
method
str := hex.EncodeToString(h.Sum(nil))
or just Sprintf the value:
func md(str string) string {
h := md5.New()
io.WriteString(h, str)
return fmt.Sprintf("%x", h.Sum(nil))
}
note that Sprintf is slower because it needs to parse the format string and then reflect based on the type found
http://play.golang.org/p/vsFariAvKo
You should avoid using the fmt
package for this. The fmt
package uses reflection, and it is expensive for anything other than debugging. You know what you have, and what you want to convert to, so you should be using the proper conversion package.
For converting from binary to hex, and back, use the encoding/hex package.
To Hex string
:
str := hex.EncodeToString(h.Sum(nil))
From Hex string
:
b, err := hex.DecodeString(str)
There are also Encode / Decode functions for []byte
.
When you need to convert to / from a decimal use the strconv package.
From int
to string
:
str := strconv.Itoa(100)
From string
to int
:
num, err := strconv.Atoi(str)
There are several other functions in this package that do other conversions (base, etc.).
So unless you're debugging or formatting an error message, use the proper conversions. Please.
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