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.
Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.
Method 1: Slicing To skip the prefix, use slicing and start with index 2 on the hexadecimal string. For example, to skip the prefix '0x' on the result of x = hex(42) ='0x2a' , use the slicing operation x[2:] that results in just the hexadecimal number '2a' without the prefix '0x' .
Python hex() FunctionThe hex() function converts the specified number into a hexadecimal value. The returned string always starts with the prefix 0x .
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
>>> integer = 2
>>> hex_string = format(integer, '#04x') # add 2 to field width for 0x
>>> hex_string
'0x02'
See Format Specification Mini-Language
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With