Convert Hex String to Int in Python
How Do I Convert a Hex String to an Int in Python? I May Have It as "0Xffff" or Just "Ffff". 1 12 Answers Without the 0X Prefix, You Need to Specify the Base...
How do I convert a hex string to an int in Python?
I may have it as "0xffff" or just "ffff".
12 Answers
Without the 0x prefix, you need to specify the base explicitly, otherwise there's no way to tell:
x = int("deadbeef", 16)
With the 0x prefix, Python can distinguish hex and decimal automatically.
>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10
(You must specify 0 as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter int() will assume base-10.)
int(hexstring, 16) does the trick, and works with and without the 0x prefix:
>>> int("a", 16)
10
>>> int("0xa", 16)
10
Convert hex string to int in Python
I may have it as
"0xffff"or just"ffff".
To convert a string to an int, pass the string to int along with the base you are converting from.
Both strings will suffice for conversion in this way:
>>> string_1 = "0xffff"
>>> string_2 = "ffff"
>>> int(string_1, 16)
65535
>>> int(string_2, 16)
65535
Letting int infer
If you pass 0 as the base, int will infer the base from the prefix in the string.
>>> int(string_1, 0)
65535
Without the hexadecimal prefix, 0x, int does not have enough information with which to guess:
>>> int(string_2, 0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 0: 'ffff'