-1

I have a decimal and write it with

hex(dezimal)

to the hex number. But I miss the 0, when i format digits 0-9

it should look like 0x09 and it looks 0x9

What can I do?

Thank you!

Sushant
  • 3,499
  • 3
  • 17
  • 34
cosmonaut
  • 414
  • 1
  • 3
  • 14
  • 1
    Possible duplicate of [Integer to Hexadecimal Conversion in Python](https://stackoverflow.com/questions/28650857/integer-to-hexadecimal-conversion-in-python) – bobrobbob Jul 09 '18 at 09:49

2 Answers2

0

You had to modify the result by your own function:

def pad_hex(s):
    return '0x' + s[2:].zfill(2)

print(pad_hex(hex(9)))

Output: 0x09

atline
  • 28,355
  • 16
  • 77
  • 113
0

If you need only to output a single byte (i.e. values from 0..255),

"{0:#04x}".format(dezimal)

gives hex output with 0x prefix.

The field length (4) applies to the entire output, i.e. including the 0x prefix. If you need variable length, then @atline's solution is more flexible.

Adrian W
  • 4,563
  • 11
  • 38
  • 52