Domanda

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,

È stato utile?

Soluzione

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top