Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python integer to hex string with padding

Tags:

python

hex

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.

like image 389
SoonSYJ Avatar asked Oct 19 '16 06:10

SoonSYJ


People also ask

How will you convert an integer to a hexadecimal string in Python?

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.

How do you remove 0x from hex in python?

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' .

How do you find the hex value in Python?

Python hex() FunctionThe hex() function converts the specified number into a hexadecimal value. The returned string always starts with the prefix 0x .


3 Answers

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

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

like image 151
Michael Kopp Avatar answered Oct 13 '22 01:10

Michael Kopp


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
like image 26
Erik Aronesty Avatar answered Oct 13 '22 02:10

Erik Aronesty


>>> integer = 2
>>> hex_string = format(integer, '#04x')  # add 2 to field width for 0x
>>> hex_string
'0x02'

See Format Specification Mini-Language

like image 38
cdlane Avatar answered Oct 13 '22 03:10

cdlane