原文引自:https://www.runoob.com/cplusplus/cpp-operators.html
在特殊情况下,可以用位运算符 & 来取代 %,从而提高程序运行效率。
这种特殊情况就是取得模是 2 的 n 次幂,如:2、4、8、16...等。
%8 和 &7 是等价的。
事实上无论把 a 换成任何范围内正整数,结果 b 都是和 c 一样的。
同理 %16 等价于 &15,%32 等价于 &31 .......
看起来适用范围并不广,所以用到最多的实际上是 &1 和 &3。
再来说一下实际优化效果。
调用取模 % 的话,通常需要 2 到 3 个运算周期,当数字太大时周期相应增加。
而使用与运算 & 的话,只需要 1 个运算周期,周期也随数字增加而增加。
对比得,运算周期减少了。
实例:
int main() { int a = 899; int b = a % 8; int c = a & 7; cout << "b=" << b << " "; cout << "c=" << c << endl; return 0; }
结果是相同的: