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

时间:2016-02-21 13:22:36

标签: python

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

我有一个文件需要阅读。但使用下面的代码只能显示ASCII

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

它可以以这种格式打印数据:

  

01201602180000020000000007000000000054000000000000 \ X0

如何将此数据转换为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

2 个答案:

答案 0 :(得分:6)

假设python3:

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

(在python2中将format(c)更改为format(ord(c))

答案 1 :(得分:1)

您只需编码为十六进制:

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

或者对于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