【问题标题】:Arranging hexadecimal horizontally水平排列十六进制
【发布时间】:2012-05-03 08:37:30
【问题描述】:

我有一个需要以十六进制显示的二进制文件。代码如下:

file=open('myfile.chn','rb')  
for x in file:     
    i=0
    while i<len(x):
        print ("%0.2X"%(x[i]))
        i=i+1
        if (i>=10): 
            i=0
            break
file.close()

我得到的结果如下:

FF  
FF  
01  
00  
01  
00  
35  
36  
49  
EC      
.   
.   
. 

为了显示结果,我需要更改代码的哪一部分?

FF FF 01 00 01   
00 35 36 49 EC  
.  
.  

(每个字节之间有一个空格)

【问题讨论】:

  • 每行只取 10 个元素有什么原因吗?
  • 是的,这只是一个例子。实际上我每行需要 32 个元素 = 16 字节。

标签: python binary hex


【解决方案1】:

因为你只需要 10 个元素,我会使用:

print(" ".join("%0.2X" % s for s in x[:10]))

或者如果你想包含整行:

print(" ".join("%0.2X" % s for s in x))

您的初始版本仍然存在错误。您的输入被读取为每行一个字符串。类型转换“%0.2X”失败(“%s”有效)。我认为您无法每行读取二进制文件。 \n 只是另一个字节,不能解释为换行符。

当您有一系列 int 值时,您可以使用 group 方法创建 n 个元素的分区。分组方法在itertools recipies中。

from itertools import zip_longest

def grouper(n, iterable):
    args = [iter(iterable)] * n
    return zip_longest(fillvalue=None, *args)

width=10
x = range(1,99)
for group in grouper(width, x):
    print((" ".join("%0.2X" % s for s in group if s)))

输出:

01 02 03 04 05 06 07 08 09 0A
0B 0C 0D 0E 0F 10 11 12 13 14
15 16 17 18 19 1A 1B 1C 1D 1E
1F 20 21 22 23 24 25 26 27 28
29 2A 2B 2C 2D 2E 2F 30 31 32
33 34 35 36 37 38 39 3A 3B 3C
3D 3E 3F 40 41 42 43 44 45 46
47 48 49 4A 4B 4C 4D 4E 4F 50
51 52 53 54 55 56 57 58 59 5A
5B 5C 5D 5E 5F 60 61 62

到 bytes_from_file 读取字节作为生成器:

def bytes_from_file(name):
    with open(name, 'rb') as fp:
        def read1(): return fp.read(1)
        for bytes in iter(read1, b""):
            for byte in bytes:
                yield byte

x = bytes_from_file('out.fmt') #replaces x = range(1,99)

【讨论】:

  • 我在 1 行中有 1600 个元素,我想将它分成每行 16 个元素,这意味着我总共有 100 行。我该怎么做?
  • 它有一个错误:无法导入名称 izip_longest。当我将 izip_longest 更改为 * 时,它还有另一个错误:未定义名称“xrange”。这在 python 3.2 中有效吗?
  • 我已将代码更改为在 python3 下运行(xrange 已消失,izip_longest 已重命名)。
【解决方案2】:

应该这样做。

for i, x in enumerate(file):
    print ("%0.2X" % (x)),
    if i > 0 and i % 5 == 0:
        print

【讨论】:

  • 它有一个错误:TypeError: %X format: a number is required, not bytes
【解决方案3】:
file=open('myfile.chn','rb')  
for x in file:

       char=0
       i=0
       while i<len(x):
           print ("%0.2X "%(x[i])),
           char += 1
           if char == 5:
               char=0
               print ''
           i=i+1
           if (i>=10): 
               i=0
               break
file.close()

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 2011-12-09
    • 2014-08-24
    • 2014-04-20
    • 2011-06-01
    • 2011-02-27
    • 1970-01-01
    • 2014-10-30
    相关资源
    最近更新 更多