0

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)
kaylum
  • 13,833
  • 2
  • 22
  • 31
  • It's totally unclear what the full context is. What is the difference between "raw bits" and "binary"? Binary is in the end just raw bits. Please show the code you have and describe in the code what is missing/incorrect. – kaylum Nov 14 '21 at 19:45
  • Sorry, that was a typo – AWESDUDE COOL Nov 14 '21 at 19:49
  • When you talk about turning it into bits, what do you mean ? hexdec = f.read() is already binary data – 0xd34dc0de Nov 14 '21 at 19:54
  • I need to read the code as individual bits (100110), the output as I understand it is in bytes – AWESDUDE COOL Nov 14 '21 at 20:05
  • When you say read the code in bits, do you mean printing 1's and 0's ? – 0xd34dc0de Nov 14 '21 at 20:08
  • Yes, printing as bits. If it's easier, I can work with hexadecimal as well. On the other end, I need to be able to turn those printed out bits/hexadecimals back into the original .UF2 file – AWESDUDE COOL Nov 14 '21 at 20:10

1 Answers1

0

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()
0xd34dc0de
  • 493
  • 4
  • 10