import struct def ch(num): if (num >= '0' and num <= '9'): return ord(num) - ord('0') elif (num >= 'A' and num <= 'F'): return ord(num) - ord('A') + 10 else: return ord(num) - ord('a') + 10 def Hex2Str(text): s = "" for i in range(0, len(text), 2): print (text[i], text[i+1]) x = ch(text[i]) * 16 + ch(text[i + 1]) print (x) try: s += struct.pack('b', x) except: s += struct.pack('B', x) print (s) return s Str = Hex2Str("000A0B0C0D0E0F112233445566778899AABBCCDDEEFF") print (type(Str)) f = open("struct.bin", "w") f.write(Str) f.close() f = open("struct2.bin", "wb") f.write(Str) f.close()
注意到上面的write格式是“w”,0A在输出时会格式化成0D0A
所以想要编辑bin文件要原样照应时,需要用“wb”