Bitwise_xor() function of NumPy module

Overview:

  • Given two numpy array-like instances the bitwise_XOR() function works pairwise on the integer/Boolean elements from each instance and performs exclusive OR operation returning the results as an ndarray. One of the parameters could also be a numpy scalar. When the input are of different dimensions the numpy broadcasting rules are applied.

  • Bitwise exclusive OR operation on two integer operands compares each pair of bits and returns 1, only if both the bits are different i.e., mutually exclusive. The result of the exclusive OR operation is zero, when the pair of bits from the operands are both zero or both one.

Example:

# Example Python program that applies
# bitwise_xor() operation between two ndarrays
import numpy

# To convert decimal numbers of the ndarray to binary numbers
convertToBinary = lambda x: numpy.binary_repr(x, width=8)
convertBase     = numpy.vectorize(convertToBinary)

# Create ndarrays of numbers and masks
numberArray = numpy.ndarray(shape = (3, 3), dtype = numpy.int32)
maskArray      = numpy.ndarray(shape = (1, 3), dtype = numpy.int32)

# Populate the numbers
count = 10
for i in range (0, 3):
    for j in range (0, 3):
        numberArray[i][j] = count
        count += 10

# Populate the masks
maskArray[0][0] = 5
maskArray[0][1] = 7
maskArray[0][2] = 9

# Apply bitwise_xor()
# As the shapes are different numpy broadcasting rules apply
XORResult = numpy.bitwise_xor(numberArray, maskArray)

print("Numbers:")
print(convertBase(numberArray))
print("Masks:")
print(convertBase(maskArray))
print("Bitwise-XORed output:")
print(convertBase(XORResult))

Output:

Numbers:
[['00001010' '00010100' '00011110']
 ['00101000' '00110010' '00111100']
 ['01000110' '01010000' '01011010']]
Masks:
[['00000101' '00000111' '00001001']]
Bitwise-XORed output:
[['00001111' '00010011' '00010111']
 ['00101101' '00110101' '00110101']
 ['01000011' '01010111' '01010011']]

 


Copyright 2024 © pythontic.com