user16541277
user16541277

Reputation:

Write/read bit-string to/from a file

I've encoded an 8x8 block of numbers using RLE and got this string of bits that I need to write to a file. The last coefficient of the sequence is padded accordingly so that the whole thing is divisible by 8.

encoded coefficients

In the image above, you can see the array of numbers, the RLE encoding(86 bits long), the padded version so its divisible by 8 (88 bits long) and the concatenated string that I am to write to a file.

0000110010001100110110111100001000111011001100010000111101111000011000110011101000100011

Would the best way to write this concatenated string be to divide the thing into 8 bit long substrings and write those individually as bytes or is there a simpler, faster way to do this? When it comes to binary data, the only module I've worked with so far is struct, this is the first time i've tackled something like this. Any and all advice would be appreciated.

Upvotes: 0

Views: 293

Answers (1)

Eli Murphy
Eli Murphy

Reputation: 66

I would convert it to a list using regex.

import re
file = open(r"insert file path here", "a")


bitstring = "0000110010001100110110111100001000111011001100010000111101111000011000110011101000100011"

bitlist = re.findall('........', bitstring) #seperates bitstring into a list of each item being 8 characters long

for i in range(len(bitlist)):
    file.write(bitlist[i])
    file.write("\n")

Let me know if this is what you mean.

I would also like to mention how pulling data from a text file will not be the most efficient way of store it. The fastest would ideally be kept in an array such as [["10110100"], ["00101010"]] and pull the data by doing...

bitarray = [["10110100"], ["00101010"]]

>>> print(bitarray[0][0])
10110100

Upvotes: 0

Related Questions