Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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]
share|improve this question
    
I'm not sure how you have 01011100b stored. Can you get the string representation? If so, list() converts a string into a list of its characters. Is that helpful? –  leekaiinthesky yesterday
    
It's an int32, I wrote it in binary to clearly show what I had in mind. Your solution might work though along with hsplit. Wonder if there is a better way without using to string –  Bartlomiej Lewandowski yesterday
    
If you don't go the string route, you'll have to do each place manually, something like this (though using 0b10000000 etc. instead of 0x...): stackoverflow.com/questions/2562308/integer-to-byte-conversion –  leekaiinthesky yesterday
1  
numpy.packbits seems relevant. –  user2357112 yesterday
    
@user2357112 I think unpackbits will solve my problem, you can add this as an answer and I'll accept this in a bit –  Bartlomiej Lewandowski yesterday

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.