十六进制到Bin:binascii.unhexlify的奇数字符串错误

时间:2018-09-21 10:59:48

标签: python python-3.x binascii

我想将像下面这样的十六进制文件转换为Binary文件,但出现此错误:我想我需要使用.strip()方法,但我不太确定!

Traceback (most recent call last):
  File ".\descrypt.py", line 27, in <module>
    main()
  File ".\descrypt.py", line 23, in main
    HexDataBin = HexToBin(HexDataOutput.strip())
  File ".\descrypt.py", line 11, in HexToBin
    binary_string = binascii.unhexlify(HexString)
binascii.Error: Odd-length string

这是十六进制文件:

01,00,00,00,d0,8c,9d,df,01,15,d1,11,8c,7a,00,c0,4f,c2,97,eb,\
01,00,00,00,d7,ab,17,ea,1a,93,80,48,90,e5,9c,7a,88,e1,69,cb,00,00,00,00,02,\
00,00,00,00,00,10,66,00,00,00,01,00,00,20,00,00,00,7e,b2,44,64,25,d4,22,21,\
1c,a1,c9,5a,fb,57,10,8a,50,a8,e1,2d,62,cb,e8,63,68,82,09,7c,98,e7,46,9e,00,\
00,00,00,0e,80,00,00,00,02,00,00,20,00,00,00,20,1c,7c,05,05,d9,9f,cd,1e,5b,\
c7,d3,8d,5e,41,14,82,3a,2b,04,7e,05,09,bb,2f,af,d8,93,fb,98,08,bc,20,00,00,\
00,7a,3e,d5,63,9e,de,99,76,2f,ff,cf,16,a7,c1,56,6f,27,ab,59,fd,f9,5b,e7,1a,\
5e,e9,f8,71,b4,d0,27,28,40,00,00,00,75,71,18,79,6d,72,39,a2,ed,42,4e,1a,f8,\
41,99,a5,9b,55,75,bb,89,d8,99,0f,72,af,49,f2,74,68,8d,11,ad,17,08,6b,8b,61,\
81,81,f7,fd,c8,95,41,cf,43,64,4c,21,94,ca,35,69,0a,56,9f,37,6a,3d,18,12,8f,\
e3

这是我的代码:

import binascii

def ReplaceHex(HexString, toReplace, newString):
   for elem in toReplace:
      if elem in HexString:
         HexString = HexString.replace(elem, newString)

return HexString

def HexToBin(HexString):
   binary_string = binascii.unhexlify(HexString)
   return HexString

def main():
   with open('target.txt', 'r') as HexFile:
      HexData = HexFile.read()

      print(HexData)

      HexDataOutput = ReplaceHex(HexData, [',', '\\'], " ")
      print(HexDataOutput)

      HexDataBin = HexToBin(HexDataOutput.strip())
      print(HexDataBin)

if __name__ == '__main__':
   main()

1 个答案:

答案 0 :(得分:0)

您还需要过滤空格符号:

import binascii
from functools import reduce

with open('target.txt', 'r') as text:
    repls = [',','\\','\n',' ']
    # remove all symbols form repls in file content
    hexline = reduce(lambda a, v: a.replace(v,''), repls, text.read())
    binaryline = binascii.unhexlify(hexline) 
    print(binaryline)