30 lines
561 B
C
30 lines
561 B
C
#include <assert.h>
|
|
#include <limits.h>
|
|
|
|
/*
|
|
* Generate mask indicating leftmost 1 in x. Assume w=32.
|
|
* For example, 0xFF00 -> 0x8000, and 0x6600 --> 0x4000.
|
|
* If x = 0, then return 0.
|
|
*/
|
|
int leftmost_one(unsigned x) {
|
|
unsigned t = x;
|
|
t >>= 1;
|
|
|
|
t |= t >> 1;
|
|
t |= t >> 2;
|
|
t |= t >> 4;
|
|
t |= t >> 8;
|
|
t |= t >> 16;
|
|
|
|
return (t + 1) & x;
|
|
}
|
|
|
|
int main() {
|
|
for (unsigned x = 0; ; x++) {
|
|
assert((x == 0 && leftmost_one(x) == 0) || (x != 0 && leftmost_one(x) == (1 << (31 - __builtin_clz(x)))));
|
|
|
|
if (x == UINT_MAX) {
|
|
break;
|
|
}
|
|
}
|
|
} |