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 number: -1
Output: Most Significant Bit (MSB) of -1 is set (1).

Required knowledge:

Basic C programming, Bitwise operator, If else

Logic:

In last post I have explained how efficiently we can check whether the 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. But here we will use bitwise AND & operator in combination with bitwise left shift << operator.

In-order to find the 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:

/**
 * 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;

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

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

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

    return 0;
} 


Output
Enter any number: -1
Most Significant Bit (MSB) of -1 is set (1).


Note: Most Significant Bit of positive numbers are always 0 and negative numbers are 1. Read more about signed number representation in computer's memory.

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