how to save actual binary numbers to file with python

Viewed 106

This is for file compression. I would like to save a binary string, for example "00011110" as that actual sequence of 1s and 0s, so that when I use Powershell's "format-hex" command to view the saved file, I will see

1E

which is the hex representation of the binary number 00011110. Rather than

00 00 00 01 01 01 01 00

which is what bytearray() would give me. It seems like there should be a simple way to do this.

1 Answers

Your problem is threefold: You must first parse the string into an integer, and then that integer has to be converted to a bytestring which can be written to a file.

file    = open(path_to_file, 'wb') # open file in binary write mode
integer = int("00011110", 2)
byte    = integer.to_bytes(1,'big') # endianness is irrelevant with a single byte
file.write(byte) # writes the single byte to the file

This should allow one to write octets in binary mode and write them directly; the file should now contain only the actual octet 00011110, or the integer 30, or the control character record separator.

Related