C Program to Check whether nth Bit is Set or not

In computer programming, bitwise operations are frequently used to manipulate individual bits in a binary representation of data. One common task is to determine whether a specific bit at a given position is set (1) or not (0). In this post, we will explore a C program that checks whether the nth bit of a number is set or not, using bitwise operations.

Problem statement

Given an integer number ‘num’ and a positive integer ‘n’, we need to determine whether the nth bit of ‘num’ is set (1) or not (0). The program should output the result based on the evaluation.

C Program to Check whether nth Bit is Set or not

#include <stdio.h>

int isNthBitSet(int num, int n) {
    // Shifting 1 by n positions to the left
    int mask = 1 << n;

    // Bitwise AND operation to check if the nth bit is set or not
    if (num & mask)
        return 1; // nth bit is set (1)
    else
        return 0; // nth bit is not set (0)
}

int main() {
    int num, n;

    printf("Enter a number: ");
    scanf("%d", &num);

    printf("Enter the position (n) of the bit to check: ");
    scanf("%d", &n);

    int result = isNthBitSet(num, n);

    printf("The %dth bit of %d is %s.\n", n, num, result ? "set" : "not set");

    return 0;
}

Input/Output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C program finds the Greatest Common Divisor (GCD) of two given numbers. Problem Statement Write a C program that...
This C program calculates the roots of a quadratic equation of the form ax^2 + bx + c = 0....
This C program allows you to find the length of a linked list, which is the number of nodes present...