The bitwise_and() function of NumPy module

The Numpy function bitwise_and() applies bitwise AND operation between the elements of two array-like instances and returns the results as an ndarray or a scalar.

Bitwise Operations Updated 24 Sep 2024 3 min read

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

Operand1Operand2Operand1 AND Operand2
000
010
100
111

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.

python
# Example Python program that applies bitwise AND operation

            # between the members two ndarray instances using the function

            # numpy.bitwise_and().

            import numpy

# Create ndarray for numbers

            numbers = numpy.ndarray(shape = (2,3), dtype=numpy.int32)

# Create ndarray for bitmasks

            masks   = numpy.ndarray(shape = (2,3), dtype=numpy.int32)

# For a given number return the binary number

            toBin = lambda x: numpy.binary_repr(x, width=5)

# Function to fill an ndarray

            def arrayInit(nparray, startVal):

                count = startVal

                for i in range (0, 2):

                    for j in range (0, 3):

                        count += 1

                        nparray[i][j] = count

# Fill numbers

            arrayInit(numbers, 20)

# Fill masks

            arrayInit(masks, 0)

# Print the numbers and the masks in binary form

            transformBase = numpy.vectorize(toBin)

            binaryNumbers = transformBase(numbers)

print("Numbers:")

            print(binaryNumbers)

print("Masks:")

            print(transformBase(masks))

# Apply bitwise AND

            print("Result of applying bitwise AND(number & mask):")

            masked = numpy.bitwise_and(numbers, masks)

            # Print the results in binary form

            print(transformBase(masked))

            print(type(masked))

Output

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