Karthik k
Karthik k

Reputation: 21

Writing bits (from a bit string) to create a binary file in python

I am new to python. Here is what I am struggling to implement. I have a very long bit string "1010101010101011111010101010111100001101010101011 ... ". I want to write this as bits and create a binary file using python. (Later I want disassemble this using IDA, this is not important for this question).

Is there any way I can write to a file at bit level (as binary)? Or do I have to convert it to bytes first and then write byte by byte? What is the best approach.

Upvotes: 1

Views: 1920

Answers (1)

Tobias
Tobias

Reputation: 1371

Yes, you have to convert it to bytes first and then write those bytes to a file. Working on a per byte basis is probably also the best idea to keep control over the ordering of your bytes (big vs. little endian), etc.

You can use int("10101110", 2) to easily convert a bit string to a numeric value. Then use a bytearray to create a sequence of all your byte values. The result will look something like this:

s = "1010101010101011111010101010111100001101010101011"
i = 0
buffer = bytearray()
while i < len(s):
    buffer.append( int(s[i:i+8], 2) )
    i += 8

# now write your buffer to a file
with open(my_file, 'bw') as f:
    f.write(buffer)

Upvotes: 2

Related Questions