显示十六进制文件的内容
#!/usr/bin/python
# -*- coding:utf-8 -*-
#s = "Hello world !!"
#":".join("{:02x}".format(ord(c)) for c in s)
header=bytes(256);
#header=[]
with open('dsp1.elf',"rb") as f:
f.seek(0,0) #SEEK_SET
header=f.read(256)
def showChr(list1):
for i in list1:
if(chr(i).isalnum()):
vv=i
print('{:2c}'.format(vv),end=' ')
else:
vv=0
print('{:2x}'.format(vv),end=' ')
print(end='\n')
#Display in decimal format
for i,v in enumerate(header):
if(i==0):
print('{:>8d}:{:3d}'.format(i,v),end='')
elif (i%16==0):
print('{:>8x}:{:3d}'.format(i,v),end='')
else:
if((i+1)%16==0):
print('{:3d}'.format(v),end='||')
showChr(header[i-15:i])
else:
print('{:3d}'.format(v),end=' ')
#Display in hex format
for i,v in enumerate(header):
if(i==0):
print('{:>8d}:{:3x}'.format(i,v),end='')
elif (i%16==0):
print('{:>8x}:{:3x}'.format(i,v),end='')
else:
if((i+1)%16==0):
print('{:3x}'.format(v),end='||')
showChr(header[i-15:i])
else:
print('{:3x}'.format(v),end=' ')
# for i,v in enumerate(header):
# if(chr(v).isalnum()):
# vv=v
# else:
# vv=0x20
# if(i==0):
# print('{:>8d}:{:3c}'.format(i,(vv)),end='')
# elif (i%16==0):
# print('{:>8x}:{:3c}'.format(i,(vv)),end='')
# else:
# if((i+1)%16==0):
# print('{:3c}'.format((vv)),end='\n')
# else:
# print('{:3c}'.format((vv)),end=' ')
#xy=int.from_bytes(header[0:4],byteorder='little',signed=False)
#print(hex(xy))
#for i,v in enumerate(header):
# if(i%16==0):
# print("{0},i={1}\n".format(hex(v),i)) #print('{0} and {1}'.format('spam', 'eggs'))
# else:
# print("{0},i={1}".format(hex(v),i))
hh=str()
for i,v in enumerate(header):
s="".join("{:02x}".format(v))
hh+=s
#print(hh[0:15])
#print(hh[16:31])
#print(header[0:15])
#print(header[16:31])
# % usage
# msg="%s->%s" %('ans',123)
本文介绍如何利用Python读取并显示十六进制格式的文件内容,帮助理解二进制文件在内存中的表示方式。

2586

被折叠的 条评论
为什么被折叠?



