Bitwise Pt. 1
As name suggests - it does bitwise manipulation
& : and, | : or, ~ : not, << : left shift, >> : right shift, ^ : xor
Bitwise AND (&) Operator
- It takes two bits at a time and perform AND operation.
- AND (&) is binary operator. It takes two numbers and perform bitwise AND.
- Result of AND is 1 when both bits are 1.
0 1 1 1 -> 7
& 0 1 0 0 -> 4
0 1 0 0 -> 4
7 & 4 = 4
Bitwise OR (|) Operator
- It takes two bits at a time and perform OR operation.
- OR (|) is binary operator. It takes two numbers and perform bitwise OR.
- Result of OR is 0 when both bits are 0.
0 1 1 1 -> 7
| 0 1 0 0 -> 4
0 1 1 1 -> 7
7 | 4 = 7
Bitwise NOT (~) Operator
-
NOT is a unary operator
-
Its job is to complement each bit one by one.
-
Result of NOT is 0 when bit is 1 and 1 when bit is 0
-
You could say :
~x == -(x + 1)
~ 0 0 0 0 0 1 1 1 -> 7
1 1 1 1 1 0 0 0 -> -8
~ 7 = -8
Difference between bitwise and logical operators
int main() {
char x = 1, y = 2; // x = 1(0000 0001), y = 2(0000 0010)
if (x & y) // 1 & 2 = 0 (0000 0000)
printf("Result of x & y is 1"); // will not be printed
if (x && y)
printf("Result of x && y is 1"); // anything other than 0 is true
return 0;
}