In Numpy, the
bitwise_and() function is mainly used to perform the
- This function will calculate the bit-wise AND of two arrays, element-wise.
bitwise_and()function calculates the bit-wise AND of the underlying binary representation of the integers in the input array.
Let us take a look at the truth table of AND operation:
If and only if both the bits are 1 only then the output of the AND result of the two bits is 1 otherwise it will be 0.
The syntax required to use this function is as follows:
numpy.bitwise_and(x1, x2, /, out, *, where=True, casting='same_kind', order='K', dtype,subok=True[, signature, extobj]) = <ufunc 'bitwise_and'>
Let us now take a look at the parameters of this function:
- x1, x2
These two are input arrays and with this function only integer and boolean types are handled. If
x1.shape != x2.shape, then they must be broadcastable to a common shape (and this shape will become the shape of the output).
This parameter mainly indicates a location in which the result is stored. If this parameter is provided, it must have a shape that the inputs broadcast to. If this parameter is either not provided or it is None then a freshly-allocated array is returned.
This parameter is used to indicate a condition that is broadcast over the input. At those locations where the condition is True, the out array will be set to the b result, else the out array will retain its original value.
This function will return a scalar if both x1 and x2 are scalars.
In the example below, we will illustrate the usage of
import numpy as np num1 = 15 num2 = 20 print ("The Input number1 is :", num1) print ("The Input number2 is :", num2) output = np.bitwise_and(num1, num2) print ("The bitwise_and of 15 and 20 is: ", output)
The input number1 is: 15
The input number2 is: 20
The bitwise_and of 15 and 20 is: 4
In the example below, we will apply the
bitwise_and() function on two arrays:
import numpy as np ar1 = [2, 8, 135] ar2 = [3, 5, 115] print ("The Input array1 is : ", ar1) print ("The Input array2 is : ", ar2) output_arr = np.bitwise_and(ar1, ar2) print ("The Output array after bitwise_and: ", output_arr)
The Input array1 is : [2, 8, 135]
The Input array2 is : [3, 5, 115]
The Output array after bitwise_and: [2 0 3]