How to go from []bytes to get hexadecimal

user2671513 picture user2671513 · Oct 12, 2013 · Viewed 51.3k times · Source

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,

Answer

fabrizioM picture fabrizioM · Oct 12, 2013

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