简体   繁体   中英

Converting .raw file into Hex

I have a .raw image file, and I'd like to use python3 to read all the data from the file and print a hex dump of this image.

If possible, i'd like it to run in the terminal window.

This is the code I have found and adapted so far:

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='.'))

I've been using the command in the terminal:

python3 nameoffile.py nameofrawfile.raw

and it just gives me the hex values of the name of the raw file. I'd like it to read the raw file then give be all the data from it in hex.

Thanks.

EDIT: I'd like to use python as once the file is represented in hex values, I'd like to do further processing on it using python.

One-liner:

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

The problem is you pass the name of the file to hexdump() which treats it like data. The following corrects that and applies other relatively minor fixes to your code (and seems to work in my limited testing):

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='.'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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