2016-12-01 70 views
0

我想做一个简单的操作,但我无法管理它。我有一个由编码算法导出的'0'和'1'字符串。我想写入文件,但我认为我做错了。如何在Python中编写/打包二进制字符串文件

我的字符串是像“11101010000 ...... 10000101010”

其实我在写一个二进制文件为:

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) 

如果我看文件的大小,我得到了很大的东西。所以我想我正在使用整个字节来写每个1和0.是否正确?

我发现了一些使用'struct'函数的例子,但我没有设法理解它是如何工作的。

谢谢!

+0

见http://stackoverflow.com/questions/142812/does-python-have-a-bitfield-type – cdarke

+0

如何你的长串是多少?他们可以转换成整数吗?我在想'int(my_coded_string,2)',然后'struct.pack()'。 – cdarke

回答

2

使用此:

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

获得字节,可追加到二进制文件的列表,

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

因为输入的二进制是串蟒蛇写道:每一位为char。 您可以从

这样与bitarray模块写你的比特流:

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 
相关问题