26 lines
628 B
C
26 lines
628 B
C
#include <stdio.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 = t >> 1;
|
|
|
|
t = t | (t >> 1);
|
|
t = t | (t >> 2);
|
|
t = t | (t >> 4);
|
|
t = t | (t >> 8);
|
|
t = t | (t >> 16);
|
|
|
|
return (t + 1) & x;
|
|
}
|
|
|
|
int main() {
|
|
printf("%.8X %.8X\n", 0x06050403, leftmost_one(0x06050403));
|
|
printf("%.8X %.8X\n", 0xF0F0F0F0, leftmost_one(0xF0F0F0F0));
|
|
printf("%.8X %.8X\n", 0x00000000, leftmost_one(0x00000000));
|
|
printf("%.8X %.8X\n", 0x00000001, leftmost_one(0x00000001));
|
|
} |