How to go from []bytes to get hexadecimal

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.

Tags:

Hash

Gravatar

Go