The bitwise operators work on bits of a integer value. Bitwise operators are used to perform bit level operations on given variables. The decimal values of the variables are converted to bits. After this the operations are performed on those bits, to understand it lets recall some basics –
p | q | p & q | p | q |
---|
0 | 0 | 0 | 0 |
0 | 1 | 0 | 1 |
1 | 1 | 1 | 1 |
1 | 0 | 0 | 1 |
Assume A = 50 and B = 10 in binary, they can be written as: A = 0011 0010 B = 0000 1010 Now in the case of A and B we compare 2 bits one from A and the corresponding bit of B And bitwise comparison A&B= 0000 0010 Or bitwise comparison A|B=0011 1010 Assume A=50, B=10
Operator | Function performed by operator | Example |
---|
& | Binary AND Operator copies a bit to the result if it exists in both operands else copies zero. | (A & B) = 2 |
| | Binary OR Operator copies a bit if it exists in either operand. | (A | B) = 58 |
^ | Bitwise exclusive OR Operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0. | (A ^ B) = 56 |
~ | Binary compliment operator i.e.- 0 changes to 1 and 1 to 0 | (~A ) = -51 |
<< | Binary Left shift Operator which rotates the number of bits to the left by specified positions as mentioned on the right. | A << 2 = 200 |
>> | Binary Right Rotation Operator which rotates the number of bits to right by specified positions as mentioned on the right. | A >> 2 = 12 |