简体   繁体   English

如何在python中将“ASCII”转换为“hex”

[英]How to convert “ASCII” to “hex” in python

How to convert "ASCII" to "HEX" in python 如何在python中将“ASCII”转换为“HEX”

I have one file need to read . 我有一个文件需要阅读。 but use below code it only can show ASCII 但使用下面的代码它只能显示ASCII

with open('Hello.DAT','rb') as f:
    data= f.read()  
    print(data)

It can print data in this format: 它可以以这种格式打印数据:

01201602180000020000000007000000000054000000000000\\x0 01201602180000020000000007000000000054000000000000 \\ X0

How do I to convert this data to HEX values, like this: 如何将此数据转换为HEX值,如下所示:

30 31 32 30 31 36 30 32 31 38 30 30 30 30 30 32 30 30 30 30 30 30 30 30 30 37 30 30 30 30 30 30 30 30 30 30 35 34 30 30 30 30 30 30 30 30 30 30 30 30 5c 78 30 30 31 32 30 31 36 30 32 31 38 30 30 30 30 30 32 30 30 30 30 30 30 30 30 37 30 30 30 30 30 30 30 30 30 30 35 34 30 30 30 30 30 30 30 30 30 30 30 30 5c 78 30

Assuming python3: 假设python3:

with open('Hello.DAT','rb') as f:
    data = f.read()  
    print(" ".join("{:02x}".format(c) for c in data))

(in python2 change format(c) to format(ord(c)) ) (以python2 format(c) format(ord(c))

You can just encode to hex: 您只需编码为十六进制:

In [6]: with open("test.txt") as f:
         print(" ".join([ch.encode("hex")  for line in f for ch in line]))
...:     
30 31 32 30 31 36 30 32 31 38 30 30 30 30 30 32 30 30 30 30 30 30 30 30 30 37 30 30 30 30 30 30 30 30 30 30 35 34 30 30 30 30 30 30 30 30 30 30 30 30 5c 78 30 0a

Or for python3 just call hex: 或者对于python3,只需调用hex:

In [18]: with open("test.txt", "rb") as f:            
            print(" ".join([hex(ch)[2:]  for line in f for ch in line]))  
 ....:     
30 31 32 30 31 36 30 32 31 38 30 30 30 30 30 32 30 30 30 30 30 30 30 30 30 37 30 30 30 30 30 30 30 30 30 30 35 34 30 30 30 30 30 30 30 30 30 30 30 30 5c 78 30 a

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM