【发布时间】:2014-01-23 04:25:42
【问题描述】:
考虑来自 Bit Twiddling Hacks 网站的 this link。 为了计算尾随位,使用了以下算法:
unsigned int v; // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v); /* THIS LINE */
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
有人可以解释一下标记为/* THIS LINE */ 的行的作用吗?更重要的是,是否可以只使用按位运算来避免使用signed()?
编辑:如何用算术/逻辑/位运算替换signed()?
【问题讨论】:
-
signed 只是类型转换,并不代表任何实际的汇编指令。
-
本世纪生产的任何 CPU 上都没有,没有。
标签: c++ algorithm c++11 bit-manipulation