C program to check Most Significant Bit (MSB) of a number is set or not

Write a C program to input any number from user and check whether the Most Significant Bit (MSB) of the given number is set (1) or not (0). How to check whether the most significant bit of any given number is set or unset using bitwise operator in C programming. C program to get the status of the most significant bit of a number.

Example

Input

Input number: -1

Output

Most Significant Bit (MSB) of -1 is set (1).

Required knowledge

Basic C programming, Bitwise operator, If else

Logic to check Most Significant Bit (MSB) of a number

In last post I have explained how to check whether Least Significant (LSB) of a number is set or not, using bitwise AND operator. Here, we will also use the same concept of bitwise AND operator to check whether the MSB of the given number is set or not. However here we will use bitwise AND & operator in combination with bitwise left shift << operator.

In-order to find status of MSB first we need to shift bits of 1 to left 31 times (if size of int is 4 bytes) or 63 times (if size is 8 bytes for long). Then perform the bitwise AND operation with the number and result evaluated in left shift operation i.e. in general we need to perform number & (1 << 31).

Program to check Most Significant Bit (MSB) of a number

/**
 * C program to check Most Significant Bit (MSB) of a number using bitwise operator
 */

#include <stdio.h>
#define INT_SIZE sizeof(int) //Since size is machine dependent

int main()
{
    int num, msb;

    // Input a number from user
    printf("Enter any number: ");
    scanf("%d", &num);

    // Move first bit set of 1 to highest order
    msb = 1 << (INT_SIZE * 8 - 1);

    //If (num & msb) evaluates to 1
    if(num & msb)
        printf("MSB of %d is set (1).", num);
    else
        printf("MSB of %d is unset (0).", num);

    return 0;
}

Important note: Most Significant Bit of positive number is always 0 and negative number is 1.

Output

Enter any number: -1
MSB of -1 is set (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>