1

I have 2-D variables (a numpy masked array, every element representing a "pixel") whose values (integers) have to be read as binaries to "unpack" the information it contains (bit 0 means this, bits 1 to 3 mean that, etc...).

I eventually want to make a test (using a numpy "where") to check whether each pixel meets certain conditions.

I might need to convert the integers to their binary representations.

For example, whether bits 4 to 6 have the value '101':

np.where(my_array_of_binaries_as_strings[-7:-4] == '101', True, False)

Is there an easy and efficient way to convert a numpy array of decimal (integers or shorts) to an array of binary representations (a string, list, integer, whatever...)? The python function "bin" does not work on arrays.

Thank you in advance! ;)

1
  • Note: integers and shorts are not decimal. Conceptually speaking, they're just numbers; in the implementation, they're binary. They have to be converted to decimal when displayed. Commented Aug 20, 2014 at 23:41

1 Answer 1

3

I think you don't need to convert them to strings at all. You can probably do this:

target      = 0b00010100
target_mask = 0b00011100

np.where(my_array_of_binaries & target_mask == target, True, False)
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed, this works really well. Moreover it is relatively fast and supports masked arrays. Thanks!
@Guiux by the way, I forgot that python actually have binary literals. I've updated the answer.

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.