1. 程式人生 > >Python向檔案寫入二進位制程式碼,字串轉換等

Python向檔案寫入二進位制程式碼,字串轉換等

Python平臺:Python 2.7

二進位制程式碼檢視工具:WinHex

 

假設我們有如下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):

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

輸出結果如下:

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檔案,確認寫入的二進位制程式碼符合