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')

2 Answers 2

5
>>> from bitarray.util import int2ba
>>> int2ba(5)
bitarray('101')

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

...Duh! I have no idea why I didn't think of that. That is obviously what it's doing. Thanks!
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.