NumPy Tutorial NumPy Statistics NumPy References

NumPy - bitwise_and() function



The Bitwise AND operator (&) is a binary operator which takes two bit patterns of equal length and performs the logical AND operation on each pair of corresponding bits. It returns 1 if both bits at the same position are 1, else returns 0.

Bit_1Bit_2Bit_1 & Bit_2
000
100
010
111

The example below describes how bitwise AND operator works:

50 & 25 gives 16

     50    ->    110010  (In Binary)
   & 25    ->  & 011001  (In Binary)
    ----        --------
     16    <-    010000  (In Binary)  

The NumPy bitwise_and() function computes the bitwise AND of two arrays element-wise. This ufunc implements the C/Python operator &.

Syntax

numpy.bitwise_and(x1, x2, out=None)

Parameters

x1, x2 Required. Specify the arrays to be operated. Only integer and boolean types are handled. If x1.shape != x2.shape, they must be broadcastable to a common shape.
out Optional. Specify a location into which the result is stored. If provided, it must have a shape that the inputs broadcast to. If not provided or None, a freshly-allocated array is returned.

Return Value

Returns the result of bitwise AND operation. This is a scalar if both x1 and x2 are scalars.

Example:

In the example below, the bitwise_and() function is used to compute the bitwise AND of two scalars.

import numpy as np

x = 50
y = 25

#Bitwise AND operation
z = np.bitwise_and(x, y)

#Displaying the result
print("z =", z)

The output of the above code will be:

z = 16

Example:

The bitwise_and() function can be used with arrays where it computes the bitwise AND of two arrays element-wise.

import numpy as np

x = np.array([[10, 20],[30, 40]])
y = np.array([[40, 30],[20, 10]])

#Bitwise AND operation
z = np.bitwise_and(x, y)

#Displaying the result
print("z =")
print(z)

The output of the above code will be:

z =
[[ 8 20]
 [20  8]]

❮ NumPy - Binary Operators