python int to hex string - Convert hex string to int in Python
int(hexString, 16) does the trick, and works with and without the 0x prefix:
>>> int("a", 16) 10 >>> int("0xa",16) 10
How do I convert a hex string to an int in Python?
I may have it as "
0xffff" or just "
Convert hex string to int in Python
I may have it as
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
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,
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'
If you're typing into source code or an interpreter, Python will make the conversion for you:
>>> integer = 0xffff >>> integer 65535
This won't work with
ffff because Python will think you're trying to write a legitimate Python name instead:
>>> integer = ffff Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'ffff' is not defined
Python numbers start with a numeric character, while Python names cannot start with a numeric character.
The worst way:
>>> def hex_to_int(x): return eval("0x" + x) >>> hex_to_int("c0ffee") 12648430
Please don't do this!
The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)
a = int('0x100', 16) print(a) #256 print('%x' % a) #100 b = a print(b) #256 c = '%x' % a print(c) #100
with '0x' prefix, you might also use eval function
>>a='0xff' >>eval(a) 255