Bitwise operators in Python

In Python, it is possible to perform bit-level operations on numbers. This is especially helpful while parsing information from certain sensors. For example, Some sensors share their output at a certain frequency. When a new data point is available, a certain bit is set indicating that the data is available. Bitwise operators can be used to check whether a particular bit is set before retrieving the datapoint from the sensor.

If you are interested in a deep dive on bitwise operators, we recommend getting started at https://en.wikipedia.org/wiki/Bitwise_operation.

Consider the numbers 3 and 2 whose binary equivalents are 011 and 010, respectively. Let's take a look at different operators that perform the operation on every bit of the number:

  • The AND operator: The AND operator is used to perform the AND operation on two numbers. Try this using the Python interpreter:
       >>>3&2 
2

This is equivalent to the following AND operation:

   0 1 1 &
0 1 0
--------
0 1 0 (the binary representation of the number 2)

  • The OR operator: The OR operator is used to perform the OR operation on two numbers as follows:
       >>>3|2 
3

This is equivalent to the following OR operation:

   0 1 1 OR
0 1 0
--------
0 1 1 (the binary representation of the number 3)
  • The NOT operator: The NOT operator flips the bits of a number. see the following example:
       >>>~1 
-2

In the preceding example, the bits are flipped, that is, 1 as 0 and 0 as 1. So, the binary representation of 1 is 0001 and when the bitwise NOT operation is performed, the result is 1110. The interpreter returns the result as -2 because negative numbers are stored as their two's complement. The two's complement of 1 is -2.

For a better understanding of two's complement and so on, we recommend reading the following articles, https://wiki.python.org/moin/BitwiseOperators and https://en.wikipedia.org/wiki/Two's_complement.
  • The XOR operator: An exclusive OR operation can be performed as follows:
       >>>3^2 
1
  • Left shift operator: The left shift operator enables shifting the bits of a given value to the left by the desired number of places. For example, bit shifting the number 3 to the left gives us the number 6. The binary representation of the number 3 is 0011. Left shifting the bits by one position will give us 0110, that is, the number 6:
       >>>3<<1 
6
  • Right shift operator: The right shift operator enables shifting the bits of a given value to the right by the desired number of places. Launch the command-line interpreter and try this yourself. What happens when you bit shift the number 6 to the right by one position?