Warm tip: This article is reproduced from stackoverflow.com, please click
encoding go hex

golang hex encode to upper case string?

发布于 2020-04-11 22:40:46

What is the best way in go to encode like: hex.EncodeToString

https://golang.org/pkg/encoding/hex/#EncodeToString

But into upper case letters?

Questioner
user29950mb89
Viewed
77
118k 2020-02-03 00:31

You may call strings.ToUpper() on the result:

src := []byte("Hello")

s := hex.EncodeToString(src)
fmt.Println(s)

s = strings.ToUpper(s)
fmt.Println(s)

Or you may use fmt.Sprintf() with %X verb:

s = fmt.Sprintf("%X", src)
fmt.Println(s)

Output of the above (try it on the Go Playground):

48656c6c6f
48656C6C6F
48656C6C6F

If performance matters, implement your own encoder. Look at the source of encoding/hex. It's really simple:

const hextable = "0123456789abcdef"

func EncodeToString(src []byte) string {
    dst := make([]byte, EncodedLen(len(src)))
    Encode(dst, src)
    return string(dst)
}

func Encode(dst, src []byte) int {
    j := 0
    for _, v := range src {
        dst[j] = hextable[v>>4]
        dst[j+1] = hextable[v&0x0f]
        j += 2
    }
    return len(src) * 2
}

Yes, all you need is to change hextable to contain the uppercased letters.