Created
December 4, 2015 16:27
-
-
Save wvega/4f9ca3d061fc165408c4 to your computer and use it in GitHub Desktop.
Convert a binary file into a binary string and back
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import struct | |
| def data_to_binary_string(input_filename): | |
| binary_string = '' | |
| file = open(input_filename, 'rb') | |
| bytes = file.read(1024) | |
| while len(bytes): | |
| binary_string = binary_string + ''.join(['{0:0>8b}'.format(ord(b)) for b in bytes]) | |
| bytes = file.read(1024) | |
| return binary_string | |
| def binary_string_to_data(binary_string, ouput_filename): | |
| bytes = [] | |
| for i in range(0, len(binary_string) / 8): | |
| bytes.append(int(binary_string[i*8:(i+1)*8], 2)) | |
| data = struct.pack('{0}B'.format(len(bytes)), *bytes) | |
| file = open(ouput_filename, 'wb') | |
| file.write(data) | |
| file.close() | |
| binary_string = data_to_binary_string('dapa.jpg') | |
| binary_string_to_data(binary_string, 'new-dapa.jpg') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment