New Tutorials:   NUMPY    TKINTER    KOTLIN    JAVASCRIPT    SASS/SCSS    PL/SQL    Matplotlib    C++ Programs
See the Tutorial List

Numpy bitwise_and() function

In this tutorial, we will cover the bitwise_and binary operation in the Numpy library.

In Numpy, the bitwise_and() function is mainly used to perform the bitwise_and operation.

  • This function will calculate the bit-wise AND of two arrays, element-wise.

  • The 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.

Syntax of bitwise_and():

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'>

Parameters:

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).

  • out
    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.

  • where
    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.

Returned Values:

This function will return a scalar if both x1 and x2 are scalars.

Example 1:

In the example below, we will illustrate the usage of bitwise_and() function:

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

Example 2:

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]

Summary

In this tutorial, we covered the bitwise_and() function of the NumPy library. We covered its basic syntax and parameters and then the values returned by this function along with some examples of this function.