bitwise operators in python

Bitwise operators treat numbers as binary. The bitwise algorithm in Python is as follows. In the following table, the variable a is 60 and b is 13. The binary format is as follows:

a = 0011 1100

b = 0000 1101

-----------------

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a  = 1100 0011

Bitwise operators include the following:

& Bitwise AND operator: two values ​​involved in the operation, if both corresponding bits are 1, the result of the bit is 1, otherwise it is 0 (a & b) output result 12, binary interpretation: 0000 1100
| Bitwise OR: As long as one of the corresponding two binary bits is 1, the result bit is 1. (a | b) Output result 61, binary interpretation: 0011 1101
^ Bitwise XOR Operator: When two corresponding binary bits are different, the result is 1 (a ^ b) output result 49, binary interpretation: 0011 0001
~ Bitwise negation operator: Negates each binary bit of the data, that is, changes 1 to 0 and 0 to 1. ~x is like -x-1 (~a ) outputs the result -61, binary interpretation: 1100 0011, in one's complement form of a signed binary number.
<< Left shift operator: All binary bits of the operand are shifted to the left by several bits, the number of bits to be shifted is specified by the number on the right of <<, the high bits are discarded, and the low bits are filled with 0. a << 2 output result 240, binary interpretation: 1111 0000
>> Right shift operator: shifts all the binary bits of the operand on the left of ">>" by a number of bits, and the number on the right of >> specifies the number of bits to move a >> 2 output result 15, binary interpretation: 0000 1111

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324661822&siteId=291194637