Reputation: 21
What is the best way in go to encode like: hex.EncodeToString
https://golang.org/pkg/encoding/hex/#EncodeToString
But into upper case letters?
Upvotes: 1
Views: 5526
Reputation: 417777
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.
Upvotes: 5