Vin*_*ent 5 c++ algorithm bit-manipulation c++11
考虑来自Bit Twiddling Hacks网站的这个链接.为了计算尾随位,使用以下算法:
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;
Run Code Online (Sandbox Code Playgroud)
有人可以解释我标记为行的角色,/* THIS LINE */更重要的是,是否可以仅使用按位运算来避免使用signed()?
编辑:如何signed()通过算术/逻辑/按位运算替换?
v &= -signed(v)将清除除1v 的最低设置位(-bit)之外的所有位,即从v中提取最低有效位1(v将随后变为幂2的数字).例如,v=14 (1110)在此之后,我们有v=2 (0010).
在这里,使用signed()是因为v是unsigned你并且你试图否定一个unsigned值(用VS2012给出编译错误)(来自JoelRondeau的评论).或者你会收到这样的警告:( warning C4146: unary minus operator applied to unsigned type, result still unsigned我的测试).