python无法从十六进制转换为二进制

时间:2014-02-11 09:58:03

标签: python binary hex ascii

我有一个必须能够将二进制文件搜索为hex或ascii的程序。我有ascii搜索/替换功能工作正常,但以前工作的十六进制搜索/替换不再工作。下面是一个正在发生的事情的例子:LH在变化之后,十六进制被转换到“ascii层”,RH是原始的。 enter image description here

包含的代码:

    if a_chars>a_digits:alphex = 'a'
else: alphex = 'h'
print alphex
# 3b. if alpha
if alphex == 'a' :
     data = open(tar,'rb').read(160); print('Opening tar file')
     if len(old)>len(new):
          old.ljust(len(old));pad = len(old)- len(new);new = new+(pad*' ')
     if len(old)<len(new):
         print 'NEW: data cannot exceed length of OLD:'
# 3c. if hex
if alphex == 'h' :
     with open(tar,'rb') as f:
          data = binascii.hexlify (f.read(100));print('Opening tar bfile')
     if len(old)>len(new): print 'OLD>NEW hex size must be ='
     if len(old)<len(new): print 'OLD<NEW hex size must be ='    
     old = old.lower();old = ''.join(old.split());print 'old: ', old 
     new = new.lower();new = ''.join(new.split());print 'new: ', new
##sub write new file
fo= open(tarname+time+'.'+tarext,'wb');print 'Creating new file...'
fo.write (data.replace(old,new));print 'Writing file...'

1 个答案:

答案 0 :(得分:0)

2月3日给我的{p> Previous answer追逐周围的树木我迷失在森林里。

data = data.replace(old,new);data = binascii.unhexlify(data)
 fo.write(data);print 'Writing bfile...'

我忘了将数据重新分配回数据(data = binascii.unhexlify(data))以获得更正的输出。