Reputation: 3347
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.
Upvotes: 9
Views: 67218
Reputation: 1
hex value is <type 'long'>
while hex string is <type 'str'>
. All operations on hex value are workable if type is changed to long from str.
long(hex_string,16)
Upvotes: 0
Reputation: 5851
I don't know the proper 'pythonic' way to do this but here was what I came up with.
def hex_string_to_bin_string(input):
lookup = {"0" : "0000", "1" : "0001", "2" : "0010", "3" : "0011", "4" : "0100", "5" : "0101", "6" : "0110", "7" : "0111", "8" : "1000", "9" : "1001", "A" : "1010", "B" : "1011", "C" : "1100", "D" : "1101", "E" : "1110", "F" : "1111"}
result = ""
for byte in input:
result = result + lookup[byte]
return result
def hex_string_to_hex_value(input):
value = hex_string_to_bin_string(input)
highest_order = len(value) - 1
result = 0
for bit in value:
result = result + int(bit) * pow(2,highest_order)
highest_order = highest_order - 1
return hex(result)
print hex_string_to_hex_value("FF")
The result being
0xff
Also trying print hex_string_to_hex_value("01234567")
results in
0x1234567L
Note: the L indicates the value falls into category of a "long" as far as I can tell based on the documentation from the python website (they do show that you can have a L value appended). https://docs.python.org/2/library/functions.html#hex
>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
>>> hex(1L)
'0x1L'
Upvotes: 0
Reputation: 137517
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
>>>
Upvotes: 17
Reputation: 133714
>>> int('01234567', 16)
19088743
This is the same as:
>>> 0x01234567
19088743
Upvotes: 6