C program to get value of nth bit of a number

Write a C program to input any number from user and check whether the nth bit of the given number is set (1) or not (0). How to check whether the 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)

Required knowledge

Basic C programming, Bitwise operator, If else

Logic to get nth bit of a number

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 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 a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    // Input 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

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>