Skip to content

NumPy - Binary Operators

NumPy provides functions for performing element-wise bitwise operations on integer arrays. These functions correspond to standard bitwise operations found in many programming languages.

The available functions are:

FunctionDescriptionEquivalent Operator
numpy.bitwise_and()Computes the bitwise AND of array elements.&
numpy.bitwise_or()Computes the bitwise OR of array elements.|
numpy.bitwise_xor()Computes the bitwise XOR of array elements.^
numpy.invert() or numpy.bitwise_not()Computes the bitwise NOT (inversion) of array elements.~
numpy.left_shift()Shifts the bits of array elements to the left.<<
numpy.right_shift()Shifts the bits of array elements to the right.>>

These operations work element-wise on NumPy arrays of integer types. You can use either the function (e.g., np.bitwise_and(a, b)) or the operator (e.g., a & b).

import numpy as np
a = np.array([10, 20, 30], dtype=np.uint8) # Binary: 00001010, 00010100, 00011110
b = np.array([ 5, 15, 25], dtype=np.uint8) # Binary: 00000101, 00001111, 00011001
result_func = np.bitwise_and(a, b)
result_op = a & b
print(f"Array a: {a}")
print(f"Array b: {b}")
print(f"np.bitwise_and(a, b): {result_func}") # 0, 4, 24
print(f"a & b: {result_op}")
import numpy as np
a = np.array([10, 20], dtype=np.uint8) # 00001010, 00010100
b = np.array([ 5, 15], dtype=np.uint8) # 00000101, 00001111
result_func = np.bitwise_or(a, b)
result_op = a | b
print(f"Array a: {a}")
print(f"Array b: {b}")
print(f"np.bitwise_or(a, b): {result_func}") # 15, 31
print(f"a | b: {result_op}")

Note: Bitwise inversion depends on the integer type (e.g., uint8, int16). For unsigned integers like uint8, it flips all 8 bits.

import numpy as np
a = np.array([10, 20], dtype=np.uint8) # Binary: 00001010, 00010100
result_func = np.invert(a)
result_op = ~a
print(f"Array a: {a}")
print(f"np.invert(a): {result_func}") # 245 (11110101), 235 (11101011)
print(f"~a: {result_op}")
import numpy as np
a = np.array([2, 8], dtype=np.uint8) # Binary: 00000010, 00001000
shift_amount = 2
result_func = np.left_shift(a, shift_amount)
result_op = a << shift_amount
print(f"Array a: {a}")
print(f"Shift amount: {shift_amount}")
print(f"np.left_shift(a, {shift_amount}): {result_func}") # 8 (00001000), 32 (00100000)
print(f"a << {shift_amount}: {result_op}")
import numpy as np
a = np.array([8, 32], dtype=np.uint8) # Binary: 00001000, 00100000
shift_amount = 2
result_func = np.right_shift(a, shift_amount)
result_op = a >> shift_amount
print(f"Array a: {a}")
print(f"Shift amount: {shift_amount}")
print(f"np.right_shift(a, {shift_amount}): {result_func}") # 2 (00000010), 8 (00001000)
print(f"a >> {shift_amount}: {result_op}")

These bitwise operations are often used in tasks involving low-level data manipulation, setting/clearing specific bits in flags, image processing masks, or implementing certain algorithms efficiently.