Darius
Darius

Reputation: 291

How to convert integer to fixed length hex string in Go?

I want to convert an integer to a hex string with a fixed length of 64 characters, prepended with zeros for integer values that do not use up all 32 hex values. If I try the following it adds spaces in front of s rather than zeros.

i := 898757
s := fmt.Sprintf("%64x", i)
fmt.Println(s)

Upvotes: 1

Views: 2224

Answers (1)

Marc
Marc

Reputation: 21055

The correct format is "%064x":

fmt.Printf("%064x\n", 898757)

00000000000000000000000000000000000000000000000000000000000db6c5

Where the leading 0 is a "flag" for the formatting string. Per the fmt docs:

0: pad with leading zeros rather than spaces; for numbers, this moves the padding after the sign

My personal preference is to use a period to separate the flags from the length field. This technically works because . is not meaningful with the integer verbs and is ignored. I find it a useful visual indicator. The format string becomes "%0.64x".

Upvotes: 4

Related Questions