2

The code in the bottom adds hexadecimal numbers to a list in the format:

['0x0', '0x1', ..., '0xa', '0xb', ..., '0xab', ...]

How can I have the single digit hexadecimal numbers have a leading zero, like this:

'0x0' '0x0a'

The code:

K = 256

keys = list(itertools.product([0, 1], repeat=8))
for poss in range(K):
    keys[poss] = hex(int(''.join(map(str, keys[poss])), 2))
A Alw
  • 41
  • 1
  • 6
  • 1
    Does this answer your question? [Decorating Hex function to pad zeros](https://stackoverflow.com/questions/12638408/decorating-hex-function-to-pad-zeros) – fas Apr 14 '20 at 11:36
  • 1
    Does this answer your question? [Python , Printing Hex removes first 0?](https://stackoverflow.com/questions/15884677/python-printing-hex-removes-first-0) – hurlenko Apr 14 '20 at 11:38

1 Answers1

3

Instead of:

hex(val)

Use:

"0x{:02x}".format(val)

Alternatively, you can use:

"0x%02x" % val

Either of these will give you a zero-padded 2-digit hex value, preceded by 0x.

Tom Karzes
  • 22,815
  • 2
  • 22
  • 41