Example:
Input number: 12
Input nth bit number: 2
Output: 2 bit of 12 is set (1).
Required knowledge:
Basic C programming, Bitwise operator, If elseBefore continuing to this post, previous two posts are highly recommended - how to check whether the LSB of a number is set or not and how to check whether the MSB of a number is set or not.
Logic:
To get the nth bit of any number we just need to right shift the number n times and then perform bitwise AND operation with the shifted number and 1. In general you may say (number >> n) & 1.Program:
/** * C program to get the nth bit of a number */ #include <stdio.h> int main() { int num, n, bitStatus; //Reads a number from user printf("Enter any number: "); scanf("%d", &num); //Reads the bit number you want to check printf("Enter nth bit to check (0-31): "); scanf("%d", &n); //Shifting bits to right n times and ANDing with 1 bitStatus = (num >> n) & 1; printf("The %d bit is set to %d", n, bitStatus); return 0; }
Note: Here I have assumed that bit ordering starts from 0.
Output
Enter any number: 12
Enter nth bit to check (0-31): 2
The 2 bit is set to 1
Enter nth bit to check (0-31): 2
The 2 bit is set to 1
Happy coding ;)
You may also like
- Bitwise operator programming exercises index.
- C program to set nth bit of a number.
- C program to clear nth bit of a number.
- C program to toggle nth bit of a number.
- C program to get highest set bit of a number.
- C program to get lowest set bit of a number.
- C program to check Least Significant Bit (LSB) of a number is set or not.
- C program to check Most Significant Bit (MSB) of a number is set or not.
- C program to count trailing zeros in a binary number.
- C program to count leading zeros in a binary number.
- C program to flip bits of a binary number using bitwise operator.