Bitwise Operators
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence the name.
Bitwise operators are applicable only for int and boolean types. By mistake if we are trying to apply for any other type then we will get Error.
& ==> Bitwise AND : If both bits are 1 then only result is 1 otherwise result is 0 | ==> Bitwise OR : If atleast one bit is 1 then result is 1 otherwise result is 0 ~ ==> Bitwise NOT : Bitwise complement operator i.e 1 means 0 and 0 means 1 ^ ==> Bitwise XOR : If bits are different then only result is 1 otherwise result is 0 >> ==> Bitwise right shift : Bitwise Right shift Operator << ==> Bitwise left shift : Bitwise Right shift Operator
E.g
x = 10 y = 4 print(x & y) print(x | y) print(~x) print(x ^ y) print(x >> 2) print(x << 2)
Output
0 14 -11 14 2 40
<< Left Shift Operator
After shifting the empty cells we have to fill with zero.
E.g
print(10<<2) 40
>> Right Shift Operator
After shifting the empty cells we have to fill with sign bit.( 0 for +ve and 1 for -ve)
E.g
print(10>>2) 2
We can apply bitwise operators for boolean types also
print(True & False) ==> False print(True | False) ==> True print(True ^ False) ==> True print(~True) ==> -2 print(True<<2) ==> 4 print(True>>2) ==> 0
Bitwise Operators