Couim
Couim

Reputation: 747

Python - write long string of bits inside a binary file

I've a string composed of ~75 000 bits (very long string).

I would like to create a binary file which is represented by this sequence of bits. I did the following code :

byte_array = bytearray(global_bits_str.encode())
with open('file1.bin', 'wb') as f:
    f.write(byte_array)

But when I check file1.bin I can see that it's composed of 75 000 bytes instead of 75 000 bits. I guess it has been encoded in ascii (1 byte per bit) in the file.

Any suggestions ?

Upvotes: 1

Views: 473

Answers (1)

tzaman
tzaman

Reputation: 47770

You can use the int builtin to convert your binary string into a sequence of integers, then pass that to bytearray.

Example for one byte:

>>> int('10101010', 2)
170
>>> bytearray([170])
bytearray(b'\xaa')

Splitting the string:

chunks = [bit_string[n:n+8] for n in range(0, len(bit_string), 8)]

You'll have to do some special casing for the last chunk since it may not be a full byte, which can be done by ljust to left-pad it with zeros.

Putting it together:

def to_bytes(bits, size=8, pad='0'):
    chunks = [bits[n:n+size] for n in range(0, len(bits), size)]
    if pad:
        chunks[-1] = chunks[-1].ljust(size, pad)
    return bytearray([int(c, 2) for c in chunks]

# Usage:
byte_array = to_bytes(global_bits_str)

Upvotes: 2

Related Questions