Python: converting a string representing an hexadecimal integer representation into an int variable
Submitted by fabio on Wed, 2010-08-11 18:27.
Recently I had the need to convert a string containing the hexadecimal representation of an integer into an integer variable.
Eg, with something like FFAA, create an integer variable with the value of 65450.
In some programming languages there is an unhex() function but not in python.
In order to do so you'll need to use int(). If called with two arguments, int() expects the first to be a string representing a number in some base and the second to be the base.
So, if you run a = int("FFAA", 16), a will be an integer having value of 65450.
Some more examples:
print int(hex(65450), 16)
print int("0xffaa", 16)
print int("ffaa", 16)
The above will produce:
65450 65450 65450
Questions, suggestions or comments? Please leave a comment below. Thanks!



Post new comment