Python - 将Hex转换为INT / CHAR [英] Python - Converting Hex to INT/CHAR
问题描述
http://home2.paulschou.net/tools/xlate/ 我输入C0A80026的十六进制转换为十六进制框,在DEC / CHAR框中,它正确输出了我期望它包含的IP。
这个数据是从外部数据库我不知道它是如何被保存的,所以我必须使用的是十六进制字符串本身。
我试过使用 binascii .unhexlify
函数来查看我是否可以解码它,但我担心我可能没有足够的理解十六进制来欣赏我正在做的事情。
试图只使用int()强制转换也没有产生所需的结果。我需要一些方法来将该十六进制字符串(或类似的)转换为原始IP。
更新:对于未来遇到此问题的任何人,我修改了以下内容答案略有提供一个确切的打印输出作为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))
如果您想从中获得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]
这可以推广,但我会把它作为练习给你。
I am having some difficulty changing a hex to an int/char (char preferably). Via the website; http://home2.paulschou.net/tools/xlate/ I enter the hex of C0A80026 into the hex box, in the DEC / CHAR box it correctly outputs the IP I expected it to contain.
This data is being pulled from an external database and I am not aware how it is being saved so all I have to work with is the hex string itself.
I have tried using the binascii.unhexlify
function to see if I could decode it but I fear that I may not have a great enough understanding of hex to appreciate what I am doing.
Attemping to print just using an int() cast also has not produced the required results. I need some way to convert from that hex string (or one similar) to the original IP.
UPDATE: For anyone who comes across this in the future I modified the below answer slightly to provide an exact printout as an IP by using;
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))
If you want to get 4 separate numbers from this, then treat it as 4 separate numbers. You don't need 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]
This can be generalised, but I'll leave it as an exercise for you.
这篇关于Python - 将Hex转换为INT / CHAR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!