【发布时间】:2010-07-21 23:22:18
【问题描述】:
给定一个已知至少设置了 2 位的 32 位 int,有没有办法有效地清除除 2 个最高有效设置位之外的所有位?即我想确保输出正好设置了 2 位。
如果保证输入只有 2 或 3 位设置怎么办?
例子:
0x2040 -> 0x2040
0x0300 -> 0x0300
0x0109 -> 0x0108
0x5040 -> 0x5000
基准测试结果:
代码:
QueryPerformanceFrequency(&freq);
/***********/
value = (base =2)|1;
QueryPerformanceCounter(&start);
for (l=0;l<A_LOT; l++)
{
//!!value calculation goes here
junk+=value; //use result to prevent optimizer removing it.
//advance to the next 2|3 bit word
if (value&0x80000000)
{ if (base&0x80000000)
{ base=6;
}
base*=2;
value=base|1;
}
else
{ value<<=1;
}
}
QueryPerformanceCounter(&end);
time = (end.QuadPart - start.QuadPart);
time /= freq.QuadPart;
printf("--------- name\n");
printf("%ld loops took %f sec (%f additional)\n",A_LOT, time, time-baseline);
printf("words /sec = %f Million\n",A_LOT/(time-baseline)/1.0e6);
在 Core2Duo E7500@2.93 GHz 上使用 VS2005 默认版本设置的结果:
--------- BASELINE
1000000 loops took 0.001630 sec
--------- sirgedas
1000000 loops took 0.002479 sec (0.000849 additional)
words /sec = 1178.074206 Million
--------- ashelly
1000000 loops took 0.004640 sec (0.003010 additional)
words /sec = 332.230369 Million
--------- mvds
1000000 loops took 0.005250 sec (0.003620 additional)
words /sec = 276.242030 Million
--------- spender
1000000 loops took 0.009594 sec (0.007964 additional)
words /sec = 125.566361 Million
--------- schnaader
1000000 loops took 0.025680 sec (0.024050 additional)
words /sec = 41.580158 Million
【问题讨论】:
-
我们说的是 32 位还是 16 位?我们必须处理的数字是多少?即低于 10 或高于 100?
-
32 位,以百万/秒的速度循环。
-
那么如果我们有 10101,那是 10000 还是 10100?
-
32 位 @ 百万:一定要去查找表!
-
感谢您的回答 - 我明天会进行基准测试。
标签: algorithm language-agnostic bit-manipulation