将.raw文件转换为十六进制

2024-05-15 20:58:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个.raw图像文件,我想用python3从文件中读取所有数据并打印这个图像的十六进制转储文件。在

如果可能的话,我希望它在终端窗口运行。在

这是迄今为止我发现并改编的代码:

import sys

src = sys.argv[1]


def hexdump( src, length=16, sep='.' ):
result = [];

# Python3 support
    try:
        xrange(0,1);
    except NameError:
        xrange = range;

    for i in xrange(0, len(src), length):
        subSrc = src[i:i+length];
        hexa = '';
        isMiddle = False;
        for h in xrange(0,len(subSrc)):
            if h == length/2:
                hexa += ' ';
            h = subSrc[h];
            if not isinstance(h, int):
                h = ord(h);
            h = hex(h).replace('0x','');
            if len(h) == 1:
                h = '0'+h;
            hexa += h+' ';
        hexa = hexa.strip(' ');
        text = '';
        for c in subSrc:
            if not isinstance(c, int):
                c = ord(c);
            if 0x20 <= c < 0x7F:
                text += chr(c);
            else:
                text += sep;
        result.append(('%08X:  %-'+str(length*(2+1)+1)+'s  |%s|') % (i, hexa, text));

    return '\n'.join(result);

if __name__ == "__main__":
    print(hexdump(src, length=16, sep='.'))

我一直在终端使用命令:

^{pr2}$

它只给我原始文件名的十六进制值。我想它读取原始文件,然后给出所有的十六进制数据。在

谢谢。在

编辑:我想使用python,因为一旦文件用十六进制值表示,我想用python对它做进一步的处理。在


Tags: 文件数据textinsrc终端forlen
2条回答

问题是将文件名传递给hexdump(),后者将其视为数据。以下内容更正了这一点,并对代码应用了其他相对较小的修复(在我有限的测试中似乎可以工作):

try:
    xrange
except NameError:  # Python3
    xrange = range

def hexdump(filename, length=16, sep='.'):
    result = []

    with open(filename, 'rb') as file:
        src = file.read()  # Read whole file into memory

    for i in xrange(0, len(src), length):
        subSrc = src[i:i+length]
        hexa = ''
        isMiddle = False;
        for h in xrange(0,len(subSrc)):
            if h == length/2:
                hexa += ' '
            h = subSrc[h]
            if not isinstance(h, int):
                h = ord(h)
            h = hex(h).replace('0x','')
            if len(h) == 1:
                h = '0'+h;
            hexa += h+' '
        hexa = hexa.strip(' ')
        text = ''
        for c in subSrc:
            if not isinstance(c, int):
                c = ord(c)
            if 0x20 <= c < 0x7F:
                text += chr(c)
            else:
                text += sep;
        result.append(('%08X:  %-'+str(length*(2+1)+1)+'s  |%s|') %
                      (i, hexa, text))

    return '\n'.join(result)

if __name__ == "__main__":
    import sys

    filename = sys.argv[1]
    print(hexdump(filename, length=16, sep='.'))

一个衬垫:

$ python -c \
"import codecs; print(codecs.encode(open('file.raw', 'rb').read(), 'hex').decode())" 

相关问题 更多 >