Python顯示二進位制檔案內容

2021-05-25 14:26:11 字數 2279 閱讀 8754

#!/usr/bin/python

import sys

import struct

import re

fname = "memory.bin"

base_addr = 0x3800000

swap = 0

def fs2_dump(start_addr, pos, size, word, fp):

index = 0

offset = 0

fp.seek(pos,0)

print

if word == 4:

while size>0:

if index == 0:

print "%08x(%04d):  " %(start_addr,offset),

start_addr = start_addr + 16

offset = offset+16

data = fp.read(4)

if len(data) == 0:

break

else:

temp = data.encode('hex')   

if swap == 1:

temp = temp[6:8]+temp[4:6]+temp[2:4]+temp[0:2]

#print "0x%08x" % struct.unpack('l',data),

print "%8s " % (temp),

index = index +1

if index == 4:

index = 0

print

size = size-4

elif word == 1:

while size>0:

if index == 0:

print "%08x(%04d):  " %(start_addr,offset),

start_addr = start_addr + 16

offset = offset+16

data = fp.read(1)

if len(data) == 0:

break

else:

temp = data.encode('hex')   

print "%2s " % (temp),

index = index +1

if index == 16:

index = 0

print

size = size-1

else:

print "word="+str(word)+" is not supported"

print

# end of function fs2_dump

#args_format = "0x3801180..+0x100"

if  len(sys.argv) < 3:

print "usage: ", sys.argv[0], "0x03800000..+0x100 word"

sys.exit()

input_args = sys.argv[1]

start = re.search("^(0x[0-9a-fa-f])/././+(0x[0-9a-fa-f])$",input_args)

#print start.groups()

read_addr = eval(start.group(1))

read_size = eval(start.group(2))

#read_addr = eval(sys.argv[1])

#read_size = eval(sys.argv[2])

#if sys.argv[3] == "word":

if sys.argv[2] == "word":

word = 4

else:

word = 1

try:

fp = open(fname, 'rb')

except ioerror:

print "failed to open"+fname

else:

offset = read_addr - base_addr

fs2_dump(read_addr, offset,read_size,word,fp)

#fp.seek(offset,0)

#(a,b,c) = struct.unpack(">iii",fp.read(4+4+4))

#print "%x %x %x" % (a,b,c)

fp.close()

#print sys.byteorder

Python 二進位制檔案讀取顯示

filename raw input enter file name f open filename,rb f.seek 0,0 index 0 for i in range 0,16 print 3s hex i print for i in range 0,16 print 3s print w...

Python 二進位制檔案讀取顯示

python view plain copy filename raw input enter file name f open filename,rb f.seek 0,0 index 0 fori inrange 0,16 print 3s hex i print fori inrange 0,...

二進位制顯示檔案

void cprocessdlg onhexshow m lfilelength file.getlength lpos file.seek loffset,cfile begin while nret file.read szbuf,m nperlinebytes 0 stemp.format t...