P 131 homework 2.65, 2.66非常有趣。我的做法是,一个用分治法,不断取相邻的1;另一个,就是受2.65的启发,变成[0...0 1...1]。(当然,不知道有无漏洞。。233)
// hw 2.65, 2.66
#include <stdio.h>
#include <stdlib.h>
// 2.65 : test if x own odd 1s
int odd_ones(unsigned x) {
x ^= x >> 1;
x ^= x >> 2;
x ^= x >> 4;
x ^= x >> 8;
x ^= x >> 16;
return x & 1;
}
// 2.66: most significant bit
int MSB(unsigned x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x - (x >> 1);
}
int main(int argc, char const *argv[]) {
printf("%d\n", odd_ones(0xfffE));
printf("%x\n", MSB(0x6600));
return 0;
}
/**
* result:
* 1
* 4000
*/