# To check a bit is set or not

This program check whether a particular bit is set or not. In this we will be seeing three approach:

Approach 1:
Right shift the number by bit given, and(&) the result with 1. If the result is 1, the given bit is set else not.

``````#include <stdio.h>

int is_set (unsigned int num, int pos)
{
return ((num >> pos) & 1);
}

int main()
{
unsigned int num, pos;
printf("\n Enter the number: ");
scanf("%d", &num);
printf("\n Enter the position: ");
scanf("%d", &pos);

int res = is_set(num, pos);
if(res)
printf("\n The given bit is set\n");
else
printf("\n The given bit is not set\n");
return 0;
}``````

Output:

`````` Enter the number: 8
Enter the position: 3

The given bit is set``````

Second Approach:
In this we do not right shift the number rather we get the another number such that all the bit if that number is 0 except the bit given. And then we and(&) the original number with the second number. If the result is 1, the given bit is set else not.

``````#include <stdio.h>
#define MAX_BIT (sizeof(int) * 8) -1

int is_set (int num, int pos)
{
/* This gives us the number where all bit is unset except at position "pos" */
int mask = 1UL << pos;
}

int main()
{
unsigned int num, pos;
printf("\n Enter the number: ");
scanf("%d", &num);
printf("\n Enter the position: ");
scanf("%d", &pos);
if (pos > MAX_BIT)
{
printf("\n Invalid bit, should be 0 - 31");
return 0;
}

int res = is_set(num, pos);
if(res)
printf("\n The given bit is set\n");
else
printf("\n The given bit is not set\n");
return 0;
}``````

Output:

`````` Enter the number: 7
Enter the position: 3

The given bit is not set``````

Third Approach:
This is similar to second approach but using macro. This is the most efficient way as there is not function call overhead but yes it does take more space.

In this the result of number and mask is right shifted to get the particular bit

``````#include <stdio.h>

#define is_set(num, pos) ((num & (1UL << pos)) >> pos)

int main()
{
unsigned int num, pos;
printf("\n Enter the number: ");
scanf("%d", &num);
printf("\n Enter the position: ");
scanf("%d", &pos);

int res = is_set(num, pos);
if(res)
printf("\n The given bit is set\n");
else
printf("\n The given bit is not set\n");
return 0;
}``````

Output:

``````Enter the number: 6

Enter the position: 0

The given bit is not set``````

Categories: C Language