NumPy Tutorial NumPy Statistics NumPy References

NumPy - bitwise_xor() function



The Bitwise XOR operator (^) is a binary operator which takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. It returns 1 if only one of the bits is 1, else returns 0.

Bit_1Bit_2Bit_1 ^ Bit_2
000
101
011
110

The example below describes how bitwise XOR operator works:

50 ^ 25 returns 43

     50    ->    110010  (In Binary)
   ^ 25    ->  ^ 011001  (In Binary)
    ----        --------
     43    <-    101011  (In Binary)  

The NumPy bitwise_xor() function computes the bitwise XOR of two arrays element-wise. This ufunc implements the C/Python operator ^.

Syntax

numpy.bitwise_xor(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 XOR operation. This is a scalar if both x1 and x2 are scalars.

Example:

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

import numpy as np

x = 50
y = 25

#Bitwise XOR operation
z = np.bitwise_xor(x, y)

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

The output of the above code will be:

z = 43

Example:

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

import numpy as np

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

#Bitwise XOR operation
z = np.bitwise_xor(x, y)

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

The output of the above code will be:

z =
[[34 10]
 [10 34]]

❮ NumPy - Binary Operators