Bitwise operators in c

these are used to perform calculations on binary numbers. addition, subtraction, addition and division are done in bit-level which makes processing faster and saves power

operatormeaning
&Bitwise AND
|Bitwise OR
^Bitwise exclusive OR
~Bitwise complement
>> &Shift right and left
Bitwise AND operator &

the output of bitwise AND will be 1,if the both operands are 1 ,if either any one is 0 , the result of corresponding to that bit is evaluated to 0.

a = 5 , b=10
c=a&b
a = 5 = 0101
b = 10= 1010
0000
c=0000=20
#include
int main()
{
int a = 5, b = 10;
printf("Output = %d", a&b);
return 0;
}
Bitwise OR operator |

this will return 1 ,when any one of the input is 1,otherwise returns zero.

a = 5 , b=10
c=a|b
a = 5 = 0101
b = 10= 1010
1111
c=1111=15=F
#include
int main()
{
int a = 5, b = 10;
printf("Output = %d", a|b);
return 0;
}
Bitwise XOR (exclusive OR) operator ^

this returns 1,when the two operands are different ,but it both are same it returns 0

a = 5 , b=10
c=a^b
a = 5 = 0101
b = 10= 1010
1111
c=1111=15=F
#include
int main()
{
int a = 5, b = 10;
printf("Output = %d", a^b);
return 0;
}
Bitwise complement operator ~

this is an unitary operator,works on one operand . It changes the 1 to 0 and 0 to 1. It is denoted by ~.

a = 0101
~a =1010
=1010
a=value (10)
Right Shift Operator >>

this is used to shift the bits in a given binary number towards right in a required no of positions ,denoted by >>

left shit operator

Left shift operator shifts all bits towards left by certain number of specified bits. It is denoted by <<.

example:

int main()
{
int num=100, i;
for (i=0; i<=2; ++i){
printf("Right shift by %d: %d\n", i, num>>i);
}
printf("\n");
for (i=0; i<=2; ++i) {
printf("Left shift by %d: %d\n", i, num<<i);
}
return 0;
}

output:

Right shift by 0: 100
Right shift by 1: 50
Right shift by 2: 25
Left shift by 0: 100
Left shift by 1: 200
Left shift by 2: 400