是否可以使用按位和受限操作符重写模(2 ^ n – 1)

前端之家收集整理的这篇文章主要介绍了是否可以使用按位和受限操作符重写模(2 ^ n – 1)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对于unsigned int x,是否可以仅使用以下运算符(加上没有循环,分支或函数调用)来计算x%255(或者一般为2 ^ n-1)?

!,〜,& ^,|,<,>>

解决方法

是的,这是可能的.对于255,可以如下进行:
  1. unsigned int x = 4023156861;
  2.  
  3. x = (x & 255) + (x >> 8);
  4. x = (x & 255) + (x >> 8);
  5. x = (x & 255) + (x >> 8);
  6. x = (x & 255) + (x >> 8);
  7.  
  8. // At this point,x will be in the range: 0 <= x < 256.
  9. // If the answer 0,x could potentially be 255 which is not fully reduced.
  10.  
  11. // Here's an ugly way of implementing: if (x == 255) x -= 255;
  12. // (See comments for a simpler version by Paul R.)
  13. unsigned int t = (x + 1) >> 8;
  14. t = !t + 0xffffffff;
  15. t &= 255;
  16. x += ~t + 1;
  17.  
  18. // x = 186

如果unsigned int是32位整数,则此操作将起作用.

编辑:该模式应该足够明显,看看如何将其推广到2 ^ n – 1.您只需要弄清楚需要多少次迭代.对于n = 8和32位整数,4次迭代应该足够了.

编辑2:

这是一个稍微更优化的版本,结合Paul R.的条件减法代码

  1. unsigned int x = 4023156861;
  2.  
  3. x = (x & 65535) + (x >> 16); // Reduce to 17 bits
  4. x = (x & 255) + (x >> 8); // Reduce to 9 bits
  5. x = (x & 255) + (x >> 8); // Reduce to 8 bits
  6. x = (x + ((x + 1) >> 8)) & 255; // Reduce to < 255

猜你在找的C&C++相关文章