Bitwise_invert() function of NumPy module

Overview:

  • The bitwise_invert() function inverts the binary bits of numpy array-like elements. It works on the Boolean and integer data types.

  • The example below prints an ndarray containing a row of positive integers and a row of their negative counterparts in binary form.

  • The ndarray is inverted using bitwise_invert() function of numpy module and the contents are printed in binary form.

  • Having a closer look on the printed ndarray instances provide the following understanding. The integers are stored in twos complement form and the bitwise_invert() inverts each bit – for positive integers and negative integers.

  • The reader could see the following in the example – for the first row containing positive integers the bits are stored: 1 as 1 and 0 as 0; for the second row containing negative integers the bits are stored: by adding 1 after inverting the bits from 0 to 1 and 1 to 0. That is how the twos complement system stores the positive and negative integers. The numpy bitwise_invert() just flips the bits in both the above cases(positive integers and negative integers).

Example:

# Example Python program that inverts the bits of ndarray elements
# using numpy.bitwise_invert
import numpy

# To print in binary form
toBinaryBits     = lambda x: numpy.binary_repr(x, width = 10)
convert         = numpy.vectorize(toBinaryBits)

# Create an ndarray
numbers = numpy.ndarray(shape = (2, 4),
                        dtype = numpy.int32)

# Not used the for loop to populate the array to
# make it easy for testing corner cases like -128
# and other numbers
numbers[0][0] = 3
numbers[0][1] = 5
numbers[0][2] = 127
numbers[0][3] = 128

numbers[1][0] = -3
numbers[1][1] = -5
numbers[1][2] = -127
numbers[1][3] = -128

# Print numbers in decimal form
print("The ndarray in decimal form:")
print(numbers)

# Print numbers in binary form
print("The ndarray in binary form:")
print(convert(numbers))

# invert
inverted = numpy.bitwise_invert(numbers)

# Print numbers in binary form
print("The inverted array:")
print(convert(inverted))

Output:

The ndarray in decimal form:
[[   3    5  127  128]
 [  -3   -5 -127 -128]]
The ndarray in binary form:
[['0000000011' '0000000101' '0001111111' '0010000000']
 ['1111111101' '1111111011' '1110000001' '1110000000']]
The inverted array:
[['1111111100' '1111111010' '1110000000' '1101111111']
 ['0000000010' '0000000100' '0001111110' '0001111111']]

 


Copyright 2024 © pythontic.com