How to go from []bytes to get hexadecimal

63,502

Solution 1

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

Solution 2

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.

Share:
63,502
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    http://play.golang.org/p/SKtaPFtnKO

    func md(str string) []byte {
        h := md5.New()
        io.WriteString(h, str)
    
        fmt.Printf("%x", h.Sum(nil))
        // base 16, with lower-case letters for a-f
        return h.Sum(nil)
    }
    

    All I need is Hash-key string that is converted from an input string. I was able to get it in bytes format usting h.Sum(nil) and able to print out the Hash-key in %x format. But I want to return the %x format from this function so that I can use it to convert email address to Hash-key and use it to access Gravatar.com.

    How do I get %x format Hash-key using md5 function in Go?

    Thanks,

  • Nick Craig-Wood
    Nick Craig-Wood over 10 years
    hex.EncodeToString is probably slightly more efficient (no reflection etc).
  • Eric Olson
    Eric Olson about 7 years
    hex.EncodeToString is about 5x faster than fmt in my benchmarking
  • Daniel Williams
    Daniel Williams over 6 years
    Maybe it's just me but %x gave me empty output and hex.EncodeToString had the expected output.
  • jws
    jws almost 3 years
    "you can import hex" -- "you can import encoding/hex" would be better