C Program to check whether ith bit in a number N is set or not

Get a number n and bit I, check whether ith bit in num is set or not.

Sample Input 1:

8 3

Sample Output 1:

Not Set

Sample Input 2:

8 1

Sample Output 2:

Set Explanation:

0000 1000

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

#include<stdio.h> int main() { //write your code here }

Program or Solution

				
			
					
#include<stdio.h>
int main()
{
	int num,bit;
	printf("Enter a number and a bit:");
	scanf("%d %d",&num,&bit);
	num=num>>(bit-1);
	if((num&1)!=0)
	{
		printf("%d is set",bit);
	}
	else
	{
		printf("%d is reset",bit);
	}
	return 0;
}
			
				
			

Program Explanation

left shift the number num by n-1 times move the nth bit to LSB.

Do AND operation between num and 1, if the LSB is 1 then output is 1, if LSB is 0 then output is 0.

Comments