Hex string variable to hex value conversion in pyt

2020-07-16 09:32发布

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.

5条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-16 09:40

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'
查看更多
叼着烟拽天下
3楼-- · 2020-07-16 09:47
>>> a
'01234567'
>>> hex(int(a))
'0x12d687'
>>> 

Hope it helps..

查看更多
虎瘦雄心在
4楼-- · 2020-07-16 09:52

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)
查看更多
乱世女痞
5楼-- · 2020-07-16 10:05

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
>>>
查看更多
Juvenile、少年°
6楼-- · 2020-07-16 10:07
>>> int('01234567', 16)
19088743

This is the same as:

>>> 0x01234567
19088743
查看更多
登录 后发表回答