2011-09-29 109 views
6

我在将十六进制更改为int/char(char最好)时遇到了一些困难。通过网站; http://home2.paulschou.net/tools/xlate/我在十六进制框中输入C0A80026的十六进制数,在DEC/CHAR框中它正确地输出了我期望它包含的IP。Python - 将Hex转换为INT/CHAR

这些数据是从外部数据库中提取的,我不知道它是如何保存的,所以我必须使用的是十六进制字符串本身。

我曾尝试使用binascii.unhexlify函数来查看我是否可以解码它,但我担心我可能没有足够的十六进制理解来欣赏我正在做的事情。

只使用int()强制转换打印也没有产生所需的结果。我需要一些方法来从该十六进制字符串(或类似的)转换为原始IP。

更新:对于任何未来遇到此问题的人,我稍微修改了下面的答案,以便通过使用提供确切的打印输出;

dec_output = str(int(hex_input[0:2], 16)) + "." + str(int(hex_input[2:4], 16)) + "." + str(int(hex_input[4:6], 16)) + "." + str(int(hex_input[6:8], 16)) 
+0

[转换十六进制字符串的可能重复在Python中为int](http://stackoverflow.com/questions/ 209513/convert-hex-string-to-int-in-python) –

+0

该解决方案不适用于我的问题 – Draineh

+0

请准确解释重复问题不是重复的。细节很重要。 “对我的问题不起作用”太模糊,无法表达任何内容。 –

回答

6

如果你想从这个获得4个独立的数字,然后把它作为4个独立的数字。你不需要binascii

hex_input = 'C0A80026' 
dec_output = [ 
    int(hex_input[0:2], 16), int(hex_input[2:4], 16), 
    int(hex_input[4:6], 16), int(hex_input[6:8], 16), 
] 
print dec_output # [192, 168, 0, 38] 

这可以是概括性的,但我会把它作为练习留给你。

+0

完美,谢谢 – Draineh

0

我希望这是你所期望的:

hex_val = 0x42424242  # hexadecimal value 
int_val = int(hex_val) # integer value 
str_val = str(int_val) # string representation of integer value 
+0

文字'0x4242422'已经创建了一个整数,'int(hex_val)'是多余的。 –

4

您可能还需要Chr函数:

chr(65) => 'A' 
+0

只接受整数问题清楚地表明,用户需要在int/char(不是int到char)中转换十六进制,而chr只接受整数,因此这不是解决方案。 –

1
>>> htext='C0A80026' 
>>> [int(htext[i:i+2],16) for i in range(0,len(htext),2)] 
# [192, 168, 0, 38] 
6

一个简单的方法

>>> s = 'C0A80026' 
>>> map(ord, s.decode('hex')) 
[192, 168, 0, 38] 
>>> 

,如果你喜欢列表理解

>>> [ord(c) for c in s.decode('hex')] 
[192, 168, 0, 38] 
>>> 
+0

不错的一个。我会将它写成一个列表理解,但这纯粹是一种品味。我喜欢使用'decode'和'ord'。 – neil

+0

谢谢@neil。我也喜欢列表解析。 –