1

My data are in the form of '32-bit unsigned integer' as follows:

myData = np.array([1073741824, 1073741877, 1073742657, 1073742709, 1073742723, 1073755137, 1073755189,1073755969],dtype=np.uint32)

I want to get the index of the elements of 'myData' where the following occurs:

Bit No. 0–1
Bit Combination: 00

How can I do it?

0

2 Answers 2

3

You can use np.binary_repr() to obtain the string representing each element and from this strings obtain the elements matching your criterion:

end = `00`
s = [np.binary_repr(ai, width=len(end)) for ai in myData]
indices = [i for (i, si) in enumerate(s) if si.endswith(end)]

EDIT: vectorized (and recommended) approach

After studying a bit more I found you can use np.unpackbits() after working with a uint8 view of your array:

myData = myData.view(np.uint32) # not needed if it is already np.uint32
tmp = np.unpackbits(myData.view(np.uint8)[::4][None, :], axis=0)
indices = np.where((tmp[-2, :] == 0) & (tmp[-1, :] == 0))[0]

Note that the slices are taken according to the bits you are comparing:

  • [::4] for the first 8 bits
  • [1::4] for the 9th to te 16th bits
  • [2::4] for the 17th to the 24th bits
  • [3::4] for the 25th to the 32th bits

this sequence could go on and on if your original data type was np.uint64, for example, but in this case using [n::8] instead.

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

Comments

1

I'd say the canonical way is this:

np.flatnonzero((a & 0b11) == 0)

I.e. mask out all bits except the last two and get the indices where it's all-zero.

This is short, fast, and doesn't make any assumption about endianness.

2 Comments

Interesting, btw how to use in case of Bit No. 5–7 and bit combination 01.
@jean - For bits 5 and 6 and pattern 01 you'd do np.flatnonzero((a & 0b110000) == 0b010000), see also this question.

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.