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.
-
The expectation of this question is that you have a hex value in ascii representation and you would like to convert the ascii representation of a hex value to a actual hex value, however the selected answer assumes a conversion from the string to a different value. The question should have really been how do I convert an Ascii value to it's hexidecimal representation (which the selected answer does). Specifically I was expecting a solution with a resulting hex value of 0x01234567onaclov2000– onaclov20002015-04-03 13:21:12 +00:00Commented Apr 3, 2015 at 13:21
5 Answers
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
>>>
3 Comments
>>> int('01234567', 16)
19088743
This is the same as:
>>> 0x01234567
19088743
2 Comments
int('0x01234567',16) also works fine, no need to remove the 0x part.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'