2

I would like to do a simple operations, but I'm not able to manage it. I have a string of '0' and '1' derived by a coding algorithm. I would like to write it to file but I think that I'm doing wrongly.

My string is something like '11101010000......10000101010'

Actually I'm writing a binary file as:

print 'WRITE TO FILE '
with open('file.bin', 'wb') as f:
    f.write(my_coded_string)

print 'READ FROM FILE' 
with open('file.bin', 'rb') as f:
    myArr = bytearray(f.read())
myArr = str(myArr)

If I look at the size of the file, I get something pretty big. So I guess that I'm using an entire byte to write each 1 and 0. Is that correct?

I have found some example which use the 'struct' function but I didn't manage to understand how it works.

Thanks!

2
  • See stackoverflow.com/questions/142812/… Commented Dec 1, 2016 at 14:46
  • How long is your string of bits? Could they be converted into integers? I'm thinking int(my_coded_string, 2), then struct.pack(). Commented Dec 1, 2016 at 14:50

2 Answers 2

4

Because input binary is string python writes each bit as a char. You can write your bit streams with bitarray module from

like this:

from bitarray import bitarray

str = '110010111010001110'

a = bitarray(str)
with open('file.bin', 'wb') as f:
    a.tofile(f)

b = bitarray()    
with open('file.bin', 'rb') as f:
    b.fromfile(f)

print b
Sign up to request clarification or add additional context in comments.

Comments

2

Use this:

import re
text = "01010101010000111100100101"
bytes = [ chr(int(sbyte,2)) for sbyte in re.findall('.{8}?', text) ]

to obtain a list of bytes, that can be append to binary file, with

with open('output.bin','wb') as f:
    f.write("".join(bytes))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.