Overview:
-
The Python NumPy function bitwise_and() applies bitwise & operation between the elements of the two given array_like objects whose elements are integers.
-
The bitwise & operation works on the binary form of the two integers.
-
Each bit of one integer is compared with the corresponding bit of the other integer. If both the bits are 1 then the resultant bit is 1. Else the resultant bit is 0. The truth table of the AND operation is given here.
-
Numpy also provides the operator & which internally uses the bitwise_and() function.
-
In addition to the array-like instances, the function bitwise_and() also accepts int and Boolean scalar types of NumPy as parameters along with Python int and Boolean types. If both the parameters are scalar, the function returns a scalar. NumPy scalars are single values of NumPy types and Python types, including class instances. The NumPy bitwise_and() works on array-likes of different shapes as long as the shapes are in accordance with the broadcasting rules of NumPy and returns an ndarray. Otherwise NumPy raises an Exception stating "ValueError: operands could not be broadcast together with shapes".
Truth table - AND :
Operand1 | Operand2 | Operand1 AND Operand2 |
---|---|---|
0 | 0 | 0 |
0 | 1 | 0 |
1 | 0 | 0 |
1 | 1 | 1 |
Example:
While printing, the example uses the numpy function binary_repr() to convert the elements of the ndarray into binary format. Using binary_repr() enables inclusion of padding bits before a binary number. The binary_repr() function accepts the width of the binary number which helps in printing the number with uniform number of digits. The Python built-in function bin() also converts a decimal number into binary form.
# Example Python program that applies bitwise AND operation # Create ndarray for numbers # Create ndarray for bitmasks # For a given number return the binary number # Function to fill an ndarray # Fill numbers # Fill masks # Print the numbers and the masks in binary form print("Numbers:") print("Masks:") # Apply bitwise AND |
Output:
Numbers: [['10101' '10110' '10111'] ['11000' '11001' '11010']] Masks: [['00001' '00010' '00011'] ['00100' '00101' '00110']] Result of applying bitwise AND(number & mask): [['00001' '00010' '00011'] ['00000' '00001' '00010']] <class 'numpy.ndarray'> |