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 calculates the volume and surface area of a sphere using its radius. A sphere is a three-dimensional...
This C program converts a Roman numeral to a decimal number. Roman numerals are a system of numerical notation used...
This C program calculates the value of sin(x) using the Taylor series expansion. The Taylor series expansion is a mathematical...