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 # To print in binary form # Create an ndarray # Not used the for loop to populate the array to numbers[1][0] = -3 # Print numbers in decimal form # Print numbers in binary form # invert # Print numbers in binary form |
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']] |