Bitwise operators are used to perform bitwise operations on binary patterns. These operators work efficiently. All the binary operators are in-fix except for the not operator.
operator | description | example |
---|---|---|
& (AND) |
The bits that are set in both operands are set. | (10101010) & (11111111) = (10101010) |
| (OR) |
The bits that are set in either of the two operands are set. | (10101010) | (11111111) = (11111111) |
^ (XOR) |
he bits that are set in only one, not both, or the operands are set. | (10101010) ^ (11111111) = (01010101) |
~ (NOT) |
Its unary operator, and the bits that are set, will be unset. | ~ (10101010) = (01010101) |
<< (SHIFT LEFT) |
It shift the bits of operand1 operand2 times to the left | (10101010) << (00000011) = (01010000) |
>> (SHIFT RIGHT) |
It shift the bits of operand1 operand2 times to the right | (10101010) >> (00000011) = (00001010) |
In the below output 0b is used to represent the binary number.
# assignment operatorsx = 12 # (00001100)y = 6 # (00000110)# The bin() function is used to print in binary format.print ('x =', x ,' and y =',y)# and operatorprint ('x & y is equal to', bin(x & y))# or operatorprint ('x | y is equal to', bin(x | y))# xor operatorprint ('x ^ y is equal to', bin(x ^ y))# shift left operatorprint ('x << y is equal to', bin(x << y))# shift right operatorprint ('x >> y is equal to', bin(x >> y))# not operatorprint ('~ x is equal to', bin(~ x ))
Free Resources