Tutorial by Examples

The & operator will perform a binary AND, where a bit is copied if it exists in both operands. That means: # 0 & 0 = 0 # 0 & 1 = 0 # 1 & 0 = 0 # 1 & 1 = 1 # 60 = 0b111100 # 30 = 0b011110 60 & 30 # Out: 28 # 28 = 0b11100 bin(60 & 30) # Out: 0b11100
The | operator will perform a binary "or," where a bit is copied if it exists in either operand. That means: # 0 | 0 = 0 # 0 | 1 = 1 # 1 | 0 = 1 # 1 | 1 = 1 # 60 = 0b111100 # 30 = 0b011110 60 | 30 # Out: 62 # 62 = 0b111110 bin(60 | 30) # Out: 0b111110
The ^ operator will perform a binary XOR in which a binary 1 is copied if and only if it is the value of exactly one operand. Another way of stating this is that the result is 1 only if the operands are different. Examples include: # 0 ^ 0 = 0 # 0 ^ 1 = 1 # 1 ^ 0 = 1 # 1 ^ 1 = 0 # 60 = 0b1111...
The << operator will perform a bitwise "left shift," where the left operand's value is moved left by the number of bits given by the right operand. # 2 = 0b10 2 << 2 # Out: 8 # 8 = 0b1000 bin(2 << 2) # Out: 0b1000 Performing a left bit shift of 1 is equivalent ...
The >> operator will perform a bitwise "right shift," where the left operand's value is moved right by the number of bits given by the right operand. # 8 = 0b1000 8 >> 2 # Out: 2 # 2 = 0b10 bin(8 >> 2) # Out: 0b10 Performing a right bit shift of 1 is equivalent...
The ~ operator will flip all of the bits in the number. Since computers use signed number representations — most notably, the two's complement notation to encode negative binary numbers where negative numbers are written with a leading one (1) instead of a leading zero (0). This means that if you w...
All of the Bitwise operators (except ~) have their own in place versions a = 0b001 a &= 0b010 # a = 0b000 a = 0b001 a |= 0b010 # a = 0b011 a = 0b001 a <<= 2 # a = 0b100 a = 0b100 a >>= 2 # a = 0b001 a = 0b101 a ^= 0b011 # a = 0b110

Page 1 of 1