65,187
社区成员




static int get_only_first_one(int x)
{
int r;
do {
r = x;
x = x & (x - 1);
} while(x);
return r;
}
这样改更好些!#include <stdio.h>
static int get_only_first_one(int x)
{
int r = x;
while(x & (x-1)) {
x = x & (x - 1);
r = x;
}
return r;
}
int main(int argg, char *argv[])
{
fprintf(stdout, "0x%08X ...\n", get_only_first_one(1));//1
fprintf(stdout, "0x%08X ...\n", get_only_first_one(2));//2
fprintf(stdout, "0x%08X ...\n", get_only_first_one(3));//2
fprintf(stdout, "0x%08X ...\n", get_only_first_one(4));//4
fprintf(stdout, "0x%08X ...\n", get_only_first_one(5));//4
fprintf(stdout, "0x%08X ...\n", get_only_first_one(6));//4
fprintf(stdout, "0x%08X ...\n", get_only_first_one(7));//4
fprintf(stdout, "0x%08X ...\n", get_only_first_one(8));//8
return 0;
}
其他情况(0、32位、64位等)楼主自己变通吧。int d=0x01010101,r;
__asm {
mov eax,d
and eax,0x11000000
mov r,eax
}
printf("0x%08x\n",r);
#include <iostream>
#define BIT(n) (1<<(n))
static unsigned int _msb(unsigned int n, int l, int r)
{
int m = (l+r)/2;
if (l==r) return l;
if (n > BIT(m)) l=m+1;
else r=m;
return _msb(n, l, r);
}
unsigned int msb(unsigned int n)
{
return n?(1<<_msb(n, 0, 8*sizeof(n)-1)):0;
}
int main(void)
{
std::cout << 0 <<": "<< msb(0) << std::endl;
for (int i=0; i<32; i++){
std::cout << i <<": "<< msb(1<<i) << std::endl;
}
return 0;
}
[root@vps616 c]# ./main
quick_proc(0x0)=0x0
quick_proc(0x1)=0x1
quick_proc(0x2)=0x2
quick_proc(0x3)=0x2
quick_proc(0x4)=0x4
quick_proc(0x5)=0x4
quick_proc(0x6)=0x4
quick_proc(0x7)=0x4
quick_proc(0x8)=0x8
quick_proc(0x9)=0x8
quick_proc(0xa)=0x8
quick_proc(0xb)=0x8
quick_proc(0xc)=0x8
quick_proc(0xd)=0x8
quick_proc(0xe)=0x8
quick_proc(0xf)=0x8
quick_proc(0x10)=0x10
quick_proc(0x11)=0x10
quick_proc(0x12)=0x10
quick_proc(0x13)=0x10
[root@vps616 c]# cat main.c
#include <stdio.h>
int quick_proc(int n) {
int off = 0;
unsigned int un = (unsigned int)n;
while (un) {
un >>= 1;
++ off;
}
if (off) {
return 1 << (off - 1);
}
return 0;
}
int main(int argc, char* const argv[]) {
#ifdef DEBUG
int n;
for (n = 0; n != 20; ++ n) {
printf("quick_proc(0x%x)=0x%x\n", (unsigned int)n, (unsigned int)quick_proc(n));
}
#endif
return 0;
}