How to check if most significant bit (MSB) of a number is set or not in C

1 Answer

0 votes
#include <stdio.h>

#define BITS sizeof(int) * 8 

int main()
{
    int n = 15, msb;

    msb = 1 << (BITS - 1);

    if (n & msb)
        printf("MSB set (1)\n");
    else
        printf("MSB not set (0)\n");
        
    msb = 1 << (4 - 1);  
    if (n & msb)
        printf("MSB set (1)\n");
    else
        printf("MSB not set (0)\n");
    
    n = -3;   
    msb = 1 << (BITS - 1);  
    if (n & msb)
        printf("MSB set (1)\n");
    else
        printf("MSB not set (0)\n");

    return 0;
}



/*
run:

MSB not set (0)
MSB set (1)
MSB set (1)

*/

 



answered Mar 31, 2019 by avibootz
edited Mar 31, 2019 by avibootz
...