-
-
Save jpgoldberg/a9b9212e5bcd43db1c4cb08395fbcbe1 to your computer and use it in GitHub Desktop.
Golang fat %x strips leading 0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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