Python - 将十六进制转换为 INT/CHAR
我在将十六进制更改为 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))
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))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果你想从中得到 4 个独立的数字,那么将其视为 4 个独立的数字。您不需要
binascii
。这可以概括,但我将其作为练习留给您。
If you want to get 4 separate numbers from this, then treat it as 4 separate numbers. You don't need
binascii
.This can be generalised, but I'll leave it as an exercise for you.
这是一个简单的方法
如果您喜欢列表理解,
A simple way
if you prefer list comprehensions
您可能还需要 chr 函数:
You might also need the chr function:
要将十六进制字符串转换为人类可读的字符串,您可以像这样转义每个十六进制字符:
从字符串您可以轻松循环到 INT 列表:
您的示例:
For converting hex-string to human readable string you can escape every HEX character like this:
from string you can easily loop to INT list:
Your example:
我希望这是你所期望的:
I hope it's what you expect: