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

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.

Procedure:

1. read a number n
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;.
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).

If bitwise AND operation num & msb evaluate to 1 then MSB of num is set otherwise not.

Program

#include<stdio.h>
#define BITS sizeof(int) * 8
int main() {
    int n,msb;
    scanf("%d",&n);
     msb = 1 << (BITS - 1);
    if(n & msb)
        printf("MSB of %d is set (1).", n);
    else
        printf("MSB of %d is unset (0).", n);
}

Input:
 -2
output:
MSB of -4 is set (1).

No comments:

Post a Comment