Question

I'm in the unique situation where searching for "most significant bit" yields too many results and I can't find an answer that fits my needs!

The question itself is pretty simple: "How do I find the most significant set bit in an unsigned long?" When I do my calculations the rightmost bit position is position '0'.

I know that it involves masking the lowest bit, checking and then shifting left to once while incrementing my count, and then repeating with the 2nd lowest, etc.

I've done this before but for whatever reason I can't do it now.


Edit: By "most significant" I mean leftmost set bit, sorry for any confusion!*


Below is my functioning solution and a few test cases:

#include <stdio.h>

int findExponent( unsigned long L ){

    int exponent = -1;

    unsigned long shift = L;

    while( 0 != shift )
        exponent++, shift >>=1;

    if ( exponent >= 0 )
        printf("The most significant bit of L is at position %d\n", exponent);
    else{
        exponent = 0;
        printf("L is zero\n");
    }
    return exponent;
}


int main(int argc, char** argv){

    long check = 8L;

    findExponent( check );//2
    findExponent( 21421L );//14
    findExponent( 0L );//(is zero)
    findExponent( 1L );//0
}
Was it helpful?

Solution

"How do I find the most significant bit in an unsigned long?"

You can do shifts to the right until the last 1 is droped. In this moment, the value becomes 0.

#include <stdio.h>
int main(void) {
          unsigned long x = 3333;
          unsigned long y = x;
          int p = -1;
          while (0 != y)
              p++, y >>= 1;
          if (p >= 0)
              printf("The most significative bit of x is at position %d\n", p);
          else
              printf("x is zero\n");
}

OTHER TIPS

Perform left shifts until the signed value is less than 0 (if ((signed long)x < 0)), then subtract the number of shifts performed from the MSb position value (or just decrement instead).

unsigned long x = val & ((~0ULL >> 1) ^ (~0ULL));

of course if the value is signed all negatives have one in the most significative bit otherwise zero :)

shift right and XOR with one's... in an 8 bit example.

0011 1100 -> val
1111 1111 -> (~0)
0111 1111 -> (~0 >> 1)
1000 0000 -> ((~0 >> 1) ^ (~0))
0000 0000 -> val & ((~0 >> 1) ^ (~0))  !most significant bit from val is zero
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top