How to go from []bytes to get hexadecimal
Asked Answered
T

3

55

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,

Theresatherese answered 11/10, 2013 at 23:56 Comment(0)
M
79

If I understood correctly you want to return the %x format:

you can import "encoding/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

Malaya answered 12/10, 2013 at 0:9 Comment(4)
hex.EncodeToString is probably slightly more efficient (no reflection etc).Echinate
hex.EncodeToString is about 5x faster than fmt in my benchmarkingHeteromerous
Maybe it's just me but %x gave me empty output and hex.EncodeToString had the expected output.Maclean
"you can import hex" -- "you can import encoding/hex" would be betterWarwickshire
C
24

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.

Communicant answered 13/10, 2013 at 16:41 Comment(0)
O
0

Some of the offered solutions have limitations when it comes to the maximum allowed size of the numbers involved.

I have read what Luke wrote about using the fmt package but still i like to add an alternative solution to this page because i did not see anyone that offered this particular method, it's really only 3 lines and i am pretty sure that this solution will also be useful for some people who visit this page somewhere in the future.

package main

import(
    "fmt"
    "math/big"
)

func main() {

    newbytes := []byte{159,127,208,150,211,126,210,192,227,247,240,207,201,36,190,239,79,252,235,104}

    newkey := new(big.Int).SetBytes(newbytes)

    fmt.Printf("%X \n", newkey)
}

Or if you just need to grab the string

package main

import(
    "fmt"
    "math/big"
)

func getHexString(bytesl []byte) (string) {

    newkey := new(big.Int).SetBytes(bytesl)

    base16str := fmt.Sprintf("%X",newkey)

    return base16str
}

func main() {

    newbytes := []byte{159,127,208,150,211,126,210,192,227,247,240,207,201,36,190,239,79,252,235,104}

    hexstr := getHexString(newbytes)

    fmt.Println(hexstr)
}

To be clear i'm not saying this is a good or the best method because that usually depends on the project environment so i just added this for completeness and demonstration purposes.

Here is yet another method using .Text(base)

    package main
    
    import(
        "fmt"
        "math/big"
    )
    
    func main() {
    
        newbytes := []byte{159,127,208,150,211,126,210,192,227,247,240,207,201,36,190,239,79,252,235,104}
    
        newkey := new(big.Int).SetBytes(newbytes)
    
// print by specifying base

        // base2
        fmt.Println(newkey.Text(2))
    
        // base10
        fmt.Println(newkey.Text(10))
    
        //base16
        fmt.Println(newkey.Text(16))
    }
Occasionally answered 14/4 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.