Search code examples
pythonstringalgorithmbinarylow-level

Converting any file to binary 1 and 0 and then back to original file without corruption in python


I need a bit help here, don't ask me why it is a wild idea but I want to convert any file into pure binary code 1 and 0 and then back to the original file. The requirement is that when converted the binary code need to be stored in a string data type in a variable and the function that takes in the binary code also accepts the code in a string data type. I would appreciate the solution in python but other languages are also welcome.

I tried to do it but when I converted back to the original file it was always corrupted. I tried to convert it to Hex and then to binary but I was not able to achieve that.


Solution

  • Here's an example Python code that can convert any file to a string of binary code and then back to the original file:

    def file_to_binary_string(file_path):
        with open(file_path, 'rb') as file:
            binary_code = file.read()
            binary_string = ''.join(format(byte, '08b') for byte in binary_code)
        return binary_string
    def binary_string_to_file(binary_string, file_path):
        with open(file_path, 'wb') as file:
            bytes_list = [int(binary_string[i:i+8], 2) for i in range(0, len(binary_string), 8)]
            bytes_arr = bytearray(bytes_list)
            file.write(bytes_arr)
    # Usage example
    file_path = 'example.pdf'
    binary_string = file_to_binary_string(file_path)
    binary_string_to_file(binary_string, 'new_example.pdf')