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 number: 12
Input nth bit number: 2
Output: 2 bit of 12 is set (1).

Required knowledge:

Basic C programming, Bitwise operator, If else
Before 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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment