scott-griffiths / bitstring

A Python module to help you manage your bits
https://bitstring.readthedocs.io/en/stable/index.html
MIT License
401 stars 67 forks source link

BitArray(random.getrandbits(128)) fails #299

Closed ThomasKundera closed 9 months ago

ThomasKundera commented 9 months ago

Hi,

Using bitstring-4.1.2-py3-none-any.whl this simple code fails:

>>> import random
>>> from bitstring import BitArray
>>> BitArray(random.getrandbits(128))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/anyone/.local/lib/python3.10/site-packages/bitstring/classes.py", line 525, in __new__
    x._initialise(__auto, length, offset, **kwargs)
  File "/home/anyone/.local/lib/python3.10/site-packages/bitstring/classes.py", line 546, in _initialise
    self._setauto(__auto, length, offset)
  File "/home/anyone/.local/lib/python3.10/site-packages/bitstring/classes.py", line 1013, in _setauto
    self._bitstore = BitStore(int(s))
  File "/home/anyone/.local/lib/python3.10/site-packages/bitstring/bitstore.py", line 75, in __new__
    return bitarray.bitarray.__new__(cls, *args, **new_kwargs)
OverflowError: cannot fit 'int' into an index-sized integer

Is this expected? Thanks.

TK.

ThomasKundera commented 9 months ago

.to_bytes() fixed it: BitArray(random.getrandbits(128).to_bytes(16,'big'))

scott-griffiths commented 9 months ago

Yes, getrandbits returns an integer, so it was trying to create a bitstring of that many bits long (which is very long!). So the failure was expected.