Hex string variable to hex value conversion in python
47,916
Solution 1
I think you might be mixing up numbers and their representations. 0x01234567
and 19088743
are the exact same thing. "0x01234567"
and "19088743"
are not (note the quotes).
To go from a string of hexadecimal characters, to an integer, use int(value, 16)
.
To go from an integer, to a string that represents that number in hex, use hex(value)
.
>>> a = 0x01234567
>>> b = 19088743
>>> a == b
True
>>> hex(b)
'0x1234567'
>>> int('01234567', 16)
19088743
>>>
Solution 2
>>> int('01234567', 16)
19088743
This is the same as:
>>> 0x01234567
19088743
Author by
drdot
Updated on July 09, 2022Comments
-
drdot almost 2 years
I have a variable call hex_string. The value could be '01234567'. Now I would like to get a hex value from this variable which is 0x01234567 instead of string type. The value of this variable may change. So I need a generic conversion method.
-
Ashwini Chaudhary almost 11 years
int('0x01234567',16)
also works fine, no need to remove the0x
part. -
jamylak almost 11 years@AshwiniChaudhary I didn't remove anything, the question says The value could be '01234567'
-
onaclov2000 about 9 yearsThe question doesn't seem to match the answer, the original question implied that a = "FF" print hex(a) >> 0xFF however none of the answers seem to solve that problem (including this one).
-
onaclov2000 about 9 yearsSorry, can't seem to edit worth a darn, but basically set a to a STRING value of FF, then do a hex operation on it, then print that, SHOULD result in printing 0xFF, however it usually results in an error complaining hex can't convert that value
-
Ayush Maheshwari almost 6 years@onaclov2000 The answer wants to say that instead of saving the value to a string and then convert it back to hex, you save the value as an integer and then convert it later to hex !