making a python bitarray from an integer - strange results!
Asked Answered
A

2

5

I'm just starting to use the bitarray package in python, and trying to make a bitarray from an integer gives me really confusing results:

>>> import bitarray
>>> bitarray.bitarray(5)
bitarray('01000')
>>> bitarray.bitarray(5)
bitarray('00010')
>>> bitarray.bitarray(5)
bitarray('00100')
>>> bitarray.bitarray(5)
bitarray('00110')

Does anyone have any idea why this would be happening??

Also: what would be a better way of making a bitarray from an int? This works, but string conversion seems like a strange way to do it...

>>> bitarray.bitarray(bin(5)[2:])
bitarray('101')

Edit: I ended up switching to bitstring, which does have an easy method of getting bitstrings from ints:

>>> bitstring.BitArray(uint=5,length=6)
BitArray('0b000101')
Anchorage answered 21/6, 2011 at 7:50 Comment(0)
C
3

bitarray.bitarray(n) creates an uninitialized array of length n.

As far as creating from an integer, bitarray doesn't appear to be particularly geared towards that, so you'll either have to use pack/unpack or loop over the individual bits to set them.

Consummation answered 21/6, 2011 at 7:55 Comment(2)
...Duh! I have no idea why I didn't think of that. That is obviously what it's doing. Thanks!Anchorage
The reason a fromint() function does not exist is that "integer" is somewhat poorly defined in Python. long() and int() are both integer types, so instead of supporting either it seems to prefer the neutral interface of .frombytes(), which it seems fairly easy to wrangle other base types into.Abelabelard
A
5
>>> from bitarray.util import int2ba
>>> int2ba(5)
bitarray('101')

From the project page under "Functions defined in bitarray.util module:".

Auric answered 19/3, 2021 at 17:16 Comment(0)
C
3

bitarray.bitarray(n) creates an uninitialized array of length n.

As far as creating from an integer, bitarray doesn't appear to be particularly geared towards that, so you'll either have to use pack/unpack or loop over the individual bits to set them.

Consummation answered 21/6, 2011 at 7:55 Comment(2)
...Duh! I have no idea why I didn't think of that. That is obviously what it's doing. Thanks!Anchorage
The reason a fromint() function does not exist is that "integer" is somewhat poorly defined in Python. long() and int() are both integer types, so instead of supporting either it seems to prefer the neutral interface of .frombytes(), which it seems fairly easy to wrangle other base types into.Abelabelard

© 2022 - 2024 — McMap. All rights reserved.