Bitwise Operators in C Programming Language

Notes:

Bitwise Operators in C Programming Language:

Bitwise Operators:
- are used to perform operation on bits (i.e. 0s and 1s)

Bitwise operators convert the given decimal number(s) to their binary equivalent number(s) first,
then they perform the operation on bits of those converted binary equivalent number(s) and then they convert and return the result of the operation as a decimal number back.

&: Bitwise And operator:
- If both LHS and RHS bits are 1 then the result will be 1, in all other cases result will be 0

|: Bitwise Or operator:
- If both LHS and RHS bits are 0 then the result will be 0, in all other cases result will be 1

^: Bitwise Exclusive Or operator:
- If both LHS and RHS are same bits then the result will be 0, otherwise the result will be 1

~: Bitwise complement operator:
-To complement a number add 1 to it and change the sign

<<: Bitwise Left Shift operator: [ firstNumber * pow(2,secondNumber) ]
- Shifts the bits of first number to the left by number of positions indicated by second number

>>: Bitwise Right Shift operator: [ firstNumber / pow(2,secondNumber) ]
- Shifts the bits of first number to the right by number of positions indicates by second number

Example Code:
#include <stdio.h>
int main()
{
printf("%d\n", 1 & 1); // 1
printf("%d\n", 1 & 0); // 0
printf("%d\n", 0 & 1); // 0
printf("%d\n", 0 & 0); // 0

printf("%d\n", 1 | 1); // 1
printf("%d\n", 1 | 0); // 1
printf("%d\n", 0 | 1); // 1
printf("%d\n", 0 | 0); // 0

printf("%d\n", 1 ^ 1); // 0
printf("%d\n", 1 ^ 0); // 1
printf("%d\n", 0 ^ 1); // 1
printf("%d\n", 0 ^ 0); // 0

printf("%d\n", 2 & 2); // 2
printf("%d\n", 2 & 5); // 0

printf("%d\n", 2 | 2); // 2
printf("%d\n", 2 | 5); // 7

printf("%d\n", 2 ^ 2); // 0
printf("%d\n", 2 ^ 5); // 7

printf("%d\n", ~2); // -3
printf("%d\n", ~5); // -6
printf("%d\n", ~(-5)); // 4

printf("%d\n", 1 << 4); // 16
printf("%d\n", 5 << 2); // 20

printf("%d\n", 16 >> 4); // 1
printf("%d\n", 20 >> 2); // 5

return 0;
}