How to check a bit is Set or Not in Embedded C ??

In Embedded programming we may need to identify a particular bit is Set or Not in many places like Interrupt Service Routine. Let us See how we can do it in the C programming Language.

Click here to know more about Bitwise (&,~,|) operators in C before going to this tutorial.

#include <stdio.h>
int main()
{
int a,b;
a = 118;/*1110110*/
b = 8;/*1000*/
if(a & b)
{
printf("3rd bit is set");
}
else
{
printf("3rd bit is not set");
}
return 0;
}

here a = 11110110 and b = 1000 
11110110
00001000  &
-----------------
00000000

So it(a &b) will return 0 (False)

#include <stdio.h>
int main()
{
int a,b;
a = 118;/*1110110*/
b = 2;/*10*/
if(a & b)
{
printf("2nd bit is set");
}
else
{
printf("2nd bit is not set");
}
return 0;
}

here a = 11110110 and b = 10 
11110110
00000010  &
-----------------
0 0000010
So it (a&b) will return 2. In C anything which is not equal to 0 is considered as True so the above program will return in "2nd bit is set"

Also Check
How to Set a particular bit ?
How to toggle a particular bit?
How to Clear a particular bit?
How to set/clear/toggle multiple bit?


Cheers!!!!
-> Let us Embed <-