简体   繁体   中英

Python: String of 1s and 0s -> binary file

I have a string of 1's and 0's in Python and I would like to write it to a binary file. I'm having a lot of trouble with finding a good way to do this.

Is there a standard way to do this that I'm simply missing?

If you want a binary file,

>>> import struct
>>> myFile=open('binaryFoo','wb')
>>> myStr='10010101110010101'
>>> x=int(myStr,2)
>>> x
76693
>>> struct.pack('i',x)
'\x95+\x01\x00'
>>> myFile.write(struct.pack('i',x))
>>> myFile.close()
>>> quit()
$ cat binaryFoo
�+$

Is this what you are looking for?

In [1]: int('10011001',2)
Out[1]: 153

Split your input into pieces of eight bits, then apply int(_, 2) and chr , then concatenate into a string and write this string to a file.

Something like...:

your_file.write(''.join(chr(int(your_input[8*k:8*k+8], 2)) for k in xrange(len(your_input)/8)))

There is a bitstring module now which does what you need.

from bitstring import BitArray

my_str = '001001111'
binary_file = open('file.bin', 'wb')
b = BitArray(bin=my_str)
b.tofile(binary_file)
binary_file.close()

You can test it from the shell in Linux with xxd -b file.bin

BITS_IN_BYTE = 8
chars = '00111110'
bytes = bytearray(int(chars[i:i+BITS_IN_BYTE], 2)
    for i in xrange(0, len(chars), BITS_IN_BYTE))
open('filename', 'wb').write(bytes)

Or you can use the array module like this

$ python
Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random,array
#This is the best way, I could think of for coming up with an binary string of 100000 
>>> binStr=''.join([str(random.randrange(0,2)) for i in range(100000)]) 
>>> len(binStr)
100000
>>> a = array.array("c", binStr)
#c is the type of data (character)
>>> with open("binaryFoo", "ab") as f:
...     a.tofile(f)
... 
#raw writing to file
>>> quit()
$ 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM