Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bitwise operations between elements in a list

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.

like image 997
havok2063 Avatar asked Sep 11 '14 20:09

havok2063


People also ask

Can you do bitwise operations in Python?

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.

When to use logical & and bitwise &?

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.


2 Answers

This works for numpy reduce:

>>> ar = numpy.array([1,17,1])
>>> numpy.bitwise_or.reduce(ar)
17
like image 31
tcarobruce Avatar answered Sep 26 '22 08:09

tcarobruce


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
like image 88
Ashwini Chaudhary Avatar answered Sep 23 '22 08:09

Ashwini Chaudhary