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 Most Significant Bit (MSB) of given number is set (1) or not (0). How to check whether Most Significant Bit of any given number is set or not 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).

Also read - Program to check Least Significant Bit (LSB) of a number.

Required knowledge

Bitwise operators, Data types, Variables and Expressions, Basic input/output, If else

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

We use bitwise AND & operator to check status of any bit. Bitwise AND operation evaluate each bit of resultant value as 1, if corresponding bit of operands is 1.

Step by step descriptive logic to check MSB of a number.

  1. Input a number from user. Store it in some variable say num.
  2. Find number of bits required to represent an integer in memory. Use sizeof() operator to find size of integer in bytes. Then multiply it by 8 to get number of bits required by integer. Store total bits in some variable say bits = sizeof(int) * 8;.

    Read more - How to find size of a data type using sizeof() operator.

  3. To get MSB of the number, move first bit of 1 to highest order. Left shift 1 bits - 1 times and store result in some variable say msb = 1 << (bits - 1).
  4. If bitwise AND operation num & msb evaluate to 1 then MSB of num is set otherwise not.

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 BITS sizeof(int) * 8 // Total bits required to represent integer

int main()
{
    int num, msb;

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

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

    /* Perform bitwise AND with msb and num */
    if(num & msb)
        printf("MSB of %d is set (1).", num);
    else
        printf("MSB of %d is unset (0).", num);

    return 0;
}

The above condition if(num & msb) is equivalent to if((num & msb) == 1).

Important note: Most Significant Bit of positive number is always 0 (in 2s complement) 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>