bitarray.to01()在字符串(Python)中不返回0和1

时间:2012-09-16 18:56:48

标签: python string hex bitarray

我使用库bitarray来管理我的位转换并用Python编写二进制文件。写入文件之前的bitarray.to01()长度为4807100171。出于某种原因,我无法理解,在从文件(b.fromfile(file))获取位然后转换为带有to01()的0和1的字符串后,我的字符串中不仅有0和1 (\x00)然后,当我使用它时,我收到此错误:

ValueError: invalid literal for int() with base 2: '0000000000000000\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

我想知道来自文件的字符串是否存在大小限制或某些问题。如果是这样,我还没有发现任何关于它的事情......

编辑:

以下是重现问题的方法:

import re
from bitarray import bitarray 

b = bitarray(4807100171)
b.setall(False) 

if re.match("^[\d]+$", b.to01()):
    print "there is only digits in this string."
else:
    print "there is not only digits in this string."

**编辑#2:

但是,如果我使用platform.architecture()sys.maxint检查我的机器,我就会知道:

In [1]: import platform, sys
In [5]: platform.architecture(), sys.maxint
Out[5]: (('64bit', ''), 9223372036854775807)

所以,这大约是2 ^ 63。怎么会在2 ^ 32处截断? 我有4GB的内存。我得到了2 ^ 32 * 1.16415e-10 * 8(因为我将它转换成字符串)〜= 4GB ......但是这是64位机器的事实呢?

1 个答案:

答案 0 :(得分:1)

你的机器上没有内存可以在这个大小的阵列上运行to01方法。该字符串将使用每个数字一个字节(至少) - 并且您有超过2 ** 32位数字。由于您没有重新调整或出现内存错误,您可能会遇到一些比特错误 - 但是......退后一步!

为什么地球上你想要一个40亿位的“0”和“1”数字?打印自己的Matrix主题赛道?

如果你需要将几十万个数字转换成0和1,寻找一些模式,或者其他什么,你最好以交互方式进行,一次转换几个字节,而不是你在那里尝试。