Python writes binary code to files, string conversion, etc.

Python Platform: Python 2.7 (tested, Python 3.6.1 is available, with minor changes required, see the end of the article for details)

Binary Code Viewing Tool: WinHex

 

Suppose we have the following hexadecimal code that needs to be written as a binary file:

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

 

So just use the bytearray.fromhex method, which directly converts 8-bit 16-bit strings into corresponding 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()

Suppose we encounter a binary string. The following is a 32-bit string:

binary_str = "10001100000000100000000000000100"
# 123 456789 123 456789 123 456789 123 456789 123 456789 12 A total of 32-bit binary digits

The following code converts a 32-bit binary STR to an 8-bit 16-bit 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

The output results are as follows:

8c020004

 

 

We will combine the previous steps and write a binary file with the content of 8c020004. Try:

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()

We open the saved binary file through WinHex to confirm that the written binary code conforms.

 

Appendix:

When Python 3.6.1 uses the above functions, we need to pay attention to the problem of float after len divided by int. float can not be accepted by range function. We need to change it as follows:

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

Tags: Python

Posted on Thu, 10 Oct 2019 07:39:19 -0700 by shae marks