9

Consider an integer 2. I want to convert it into hex string '0x02'. By using python's built-in function hex(), I can get '0x2' which is not suitable for my code. Can anyone show me how to get what I want in a convenient way? Thank you.

1
  • 3
    Your description is not clear. If 2 will be 0x02, how about 20? Should it be 0x014?
    – Kir Chou
    Oct 19, 2016 at 6:42

3 Answers 3

27
integer = 2
hex_string = '0x{:02x}'.format(integer)

See pep 3101, especially Standard Format Specifiers for more info.

1
  • 1
    You can omit the 0x and put a # in first place of the format string: '{:#02x}'.format(integer). "this option adds the prefix respective '0b', '0o', or '0x' to the output value" (from docs.python.org/3.7/library/string.html)
    – DaJunkie
    Oct 23, 2019 at 14:06
6

For integers that might be very large:

integer = 2
hex = integer.to_bytes(((integer.bit_length() + 7) // 8),"big").hex()

The "big" refers to "big endian"... resulting in a string that is aligned visually as a human would expect.

You can then stick "0x" on the front if you want.

hex = "0x" + hex
2
  • minor bracketing error. Should be hex = integer.to_bytes(((integer.bit_length() + 7) // 8),"big").hex()
    – Paul Smith
    Oct 15, 2018 at 13:05
  • Please, mention that your solution is python3 only: 'int' object has no attribute 'to_bytes'.
    – Yuki
    Apr 3, 2019 at 17:58
5
>>> integer = 2
>>> hex_string = format(integer, '#04x')  # add 2 to field width for 0x
>>> hex_string
'0x02'

See Format Specification Mini-Language

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.