Skip to content

Instantly share code, notes, and snippets.

@jpgoldberg
Created May 16, 2022 23:26
Show Gist options
  • Save jpgoldberg/a9b9212e5bcd43db1c4cb08395fbcbe1 to your computer and use it in GitHub Desktop.
Save jpgoldberg/a9b9212e5bcd43db1c4cb08395fbcbe1 to your computer and use it in GitHub Desktop.
Golang fat %x strips leading 0
// hex formater with %x can lose a leading 0
// This can produce strings with an odd number of hex digits
package main
import (
"encoding/binary"
"encoding/hex"
"fmt"
)
func main() {
var foo uint16 = 0x0ABC // decimal 2748
with_pct := fmt.Sprintf("%x", foo)
fmt.Printf("With string formatter: %q\n", with_pct)
// Outputs: With string formatter: "abc"
// I hope there is a cleaner way to get an integer into a []byte
foo_bytes := make([]byte, 2)
binary.BigEndian.PutUint16(foo_bytes, foo)
with_bytes := hex.EncodeToString(foo_bytes)
fmt.Printf("With hex encoding: %q\n", with_bytes)
// Outputs: With hex encoding: "0abc"
}
// Play with this in Go playground: https://go.dev/play/p/tpmlYfq7NYF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment