简体   繁体   English

Python:1s和0s的字符串 - >二进制文件

[英]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. 我在Python中有一个1和0的字符串,我想将它写入二进制文件。 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. 将输入拆分为8位,然后应用int(_, 2)chr ,然后连接成一个字符串并将此字符串写入文件。

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 您可以使用xxd -b file.bin在Linux中测试它

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 或者您可以像这样使用array模块

$ 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()
$ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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