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
}