【问题标题】:bitarray.to01() doesn't return only 0s and 1s in string (Python)bitarray.to01() 不只返回字符串中的 0 和 1(Python)
【发布时间】:2012-09-09 02:34:47
【问题描述】:

我使用库 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 位机器呢?

【问题讨论】:

  • \x00 是字符串中 NUL 字符的字符串表示形式。
  • 您正试图获取bit_array 的整数,但您的代码中没有任何地方显示bit_array 的分配位置。
  • 我刚刚添加了一行...
  • 我正在研究在创建过程中可能存在一些 null 的可能性。如果发生这种情况,我会通知你的。
  • NameError: name 'bit_array' is not defined。遵循SSCCE 的原则让生活更轻松。

标签: python string hex bitarray


【解决方案1】:

您的机器上没有内存来在该大小的位数组上运行to01 方法。该字符串将使用每个数字一个字节(至少) - 你有超过 2**32 位数字。由于您没有进行交换或内存不足错误,因此您可能在 bitarray 中遇到了一些错误- 但是……后退!

您到底为什么想要一个由“0”和“1”组成的 40 亿位数字字符串?为自己打印一个以 Matrix 为主题的赛道??

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

【讨论】:

  • 这似乎是一个测试程序的简单出路。但是,我必须同意你的看法。我会考虑把它拆成碎片。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-27
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 2018-05-15
  • 2015-09-04
相关资源
最近更新 更多