简体   繁体   中英

Python integer to hex string with padding

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.

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

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

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

The answer is Python's built-in method hex .

>>> a = hex( 23456 )
>>> type( a ) 
<type 'str'>
>>> a
'0x5ba0'
>>> integer = 2
>>> hex_string = format(integer, '#04x')  # add 2 to field width for 0x
>>> hex_string
'0x02'

See Format Specification Mini-Language

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM