Search code examples
pythonbytebitcompiled

Python- Compiled firmware to bits back to compiled firmware


I need to transfer compiled code into raw bits, then back into compiled code, for a project. I have gotten my .uf2 file into Python, and I have gotten it to show as bytes and as encoded into ANSI text, but I haven't figured out how to turn it into bits. I can add that output here, but it is incredibly long so for readability I left it out. By extension, I also haven't figured out how to turn it back into a functioning .uf2 file. Does anyone have any ideas? Is it even possible to take compiled code and turn it bits without destroying it?

Edit: Here is my code so far. I need to be able to access the bits, not the bytes. Data is encoded in ANSI.

fpath= input("File path: ")

f = open(fpath,'rb')
hexdec = f.read()
print(hexdec)
decode = hexdec.decode('ansi')
print(decode)

Solution

  • You can convert a hex string to a byte array using the fromhex() method of bytearray

    Then it's a simple matter of writing back the binary file

    binary_data = bytearray.fromhex(hex_string)
    newfile = open(path, 'wb')
    newFile.write(binary_data)
    newFile.close()