Find most significant set bit in a long

放肆的年华 提交于 2019-12-02 08:19:42

"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");
}

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!