I have a of list of bitwise elements, e.g. [1,1,1], and I want to do a bitwise OR operation between every element in the list. So, e.g.
for [1,1,1] do
1 | 1 | 1 = 1
or for [1,17,1] do
1 | 17 | 1 = 17
How can I do this without looping? Numpy's bitwise_or only seems to work on 2 arrays. Is there a bitwise & or | that works on every element, similar to sum, or np.mean? Thanks.
In Python, bitwise operators are used to performing bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit, hence the name bitwise operators.
The logical AND operator works on Boolean expressions, and returns Boolean values only. The bitwise AND operator works on integer, short int, long, unsigned int type data, and also returns that type of data.
This works for numpy reduce:
>>> ar = numpy.array([1,17,1])
>>> numpy.bitwise_or.reduce(ar)
17
You can use reduce
with operator.ior
:
>>> from operator import ior
>>> lst = [1, 17, 1]
>>> reduce(ior, lst)
17
And as suggested by @DSM in comments the numpy equivalent will be:
>>> import numpy as np
>>> arr = np.array(lst)
>>> np.bitwise_or.reduce(arr)
17
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With