官术网_书友最值得收藏!

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 pe 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 .

  • 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?
主站蜘蛛池模板: 武义县| 大同市| 武安市| 四平市| 北京市| 交口县| 深泽县| 沈丘县| 调兵山市| 勐海县| 新野县| 孟津县| 乡城县| 罗平县| 奇台县| 福建省| 宿迁市| 诸城市| 重庆市| 临朐县| 康平县| 玛沁县| 金塔县| 诏安县| 吉林省| 克拉玛依市| 永康市| 湘乡市| 南通市| 雅江县| 吴桥县| 哈尔滨市| 潼南县| 永善县| 柳州市| 习水县| 陇西县| 怀安县| 探索| 锡林浩特市| 木里|