Python向文件写入二进制代码,字符串转换等

Python平台:Python 2.7(经测试,Python3.6.1可用,须要添加少量改动,详见文章末尾)python

二进制代码查看工具:WinHexide

 

假设咱们有以下16进制代码,须要当成binary文件写入:函数

output_code = """00400000,24090002
00400004,21280004
00400008,00082021
0040000c,24020001
00400010,0000000c"""

 

那么只须要使用bytearray.fromhex方法,它会直接将8位16进制的字符串转换成相应binary:工具

file1 = open('byte_file', 'wb')

output_code = output_code.split('\n')
for line in output_code:
    print line
    file1.write(bytearray.fromhex(line.split(',')[0]))
    file1.write(bytearray.fromhex(line.split(',')[1]))
file1.close()

假设咱们遇到的是2进制字符串咋办呢?下面是一个32位的字符串:测试

binary_str = "10001100000000100000000000000100"
# ----------> 123456789 123456789 123456789 12一共32位2进制数字

下面的代码能把32位的2进制str,转换成8位的16进制str(2^32 == 16^8):code

def transfer_32binary_code(opcode_in):
    optcode_str = ''
    for i in range(len(opcode_in) / 4):
        small_xe = opcode_in[4 * i: 4 * (i + 1)]
        small_xe = hex(int(small_xe, 2))
        optcode_str += small_xe[2]
    return optcode_str

输出结果以下:blog

8c020004

 

 

咱们将前面的步骤结合起来,写入一个binary文件,内容为8c020004,试一试:字符串

file1 = open('hex_16_str.binary', 'wb')
hex_16_str = transfer_32binary_code('10001100000000100000000000000100')
print hex_16_str
file1.write(bytearray.fromhex(hex_16_str))
file1.close()

咱们经过WinHex打开保存的binary文件,确认写入的二进制代码符合it

 

附录:class

Python3.6.1使用以上功能的时候,须要注意len除以int后是float的问题,float不能被range函数接收,须要改动以下:

def transfer_32binary_code(opcode_in):
    optcode_str = ''
    for i in range(int(len(opcode_in) / 4)):  # in python 3.6.1, int divide by int is float
        small_xe = opcode_in[4 * i: 4 * (i + 1)]
        small_xe = hex(int(small_xe, 2))
        optcode_str += small_xe[2]
    return optcode_str
相关文章
相关标签/搜索