Reputation: 11170
I have an array that maps the cells in a game of life. So far I have an int for every single cell. To minimize the amount of reads I want to compress the array to whole 8 cells per 1 integer.
The problem arises when I want to create a bitmap, which expects an array of 0 and 1 like in the previous case.
Is there any quick way in numpy to convert this? I could you a loop for this but there might be a better way.
Example:
[01011100b, 0x0] -> [0, 1, 0, 1, 1, 1, 0 ,0, 0,0,0,0,0,0,0,0]
Upvotes: 2
Views: 4607
Reputation: 280182
numpy.packbits
and numpy.unpackbits
are a pretty close match for what you're looking for:
>>> numpy.packbits([1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1])
array([225, 184], dtype=uint8)
>>> numpy.unpackbits(array([225, 184], dtype=numpy.uint8))
array([1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0], dtype=uint8)
Note that numpy.unpackbits(numpy.packbits(x))
won't have the same length as x
if len(x)
wasn't a multiple of 8; the end will be padded with zeros.
Upvotes: 2