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
相關文章
相關標籤/搜索