Write a C program to input any number from user and check whether nth bit of the given number is set (1) or not (0). How to check whether nth bit of a given number is set or unset using bitwise operator in C programming. C program to get the status of nth bit of a number.
Example
Input
Input number: 12 Input nth bit number: 2
Output
2 bit of 12 is set (1)
In previous two exercise, we learned to get Least Significant Bit (LSB) and Most Significant Bit (MSB) of a number. In this post we will learn to get nth bit of a number.
Required knowledge
Bitwise operators, Data types, Variables and Expressions, Basic input/output
Logic to get nth bit of a number
Step by step descriptive logic to get nth bit of a number.
- Input number from user. Store it in some variable say num.
- Input the bit position from user. Store it in some variable say n.
- To get the nth bit of num right shift num, n times. Then perform bitwise AND with 1 i.e.
bitStatus = (num >> n) & 1;
.
Program to get nth bit of a number
/**
* C program to get the nth bit of a number
*/
#include <stdio.h>
int main()
{
int num, n, bitStatus;
/* Input number from user */
printf("Enter any number: ");
scanf("%d", &num);
/* Input bit position you want to check */
printf("Enter nth bit to check (0-31): ");
scanf("%d", &n);
/* Right shift num, n times and perform bitwise AND with 1 */
bitStatus = (num >> n) & 1;
printf("The %d bit is set to %d", n, bitStatus);
return 0;
}
Always remember bit order starts from 0.
Output
Enter any number: 12 Enter nth bit to check (0-31): 2 The 2 bit is set to 1
Happy coding 😉