Oxd*_*eef 11 c bit-manipulation modulo
对于unsigned int x,是否可以仅使用以下运算符(加上没有循环,分支或函数调用)来计算x%255(或者通常为2 ^ n - 1)?
!,~,&,^,|,+,<<,>>.
Mys*_*ial 10
是的,这是可能的.对于255,可以按如下方式完成:
unsigned int x = 4023156861;
x = (x & 255) + (x >> 8);
x = (x & 255) + (x >> 8);
x = (x & 255) + (x >> 8);
x = (x & 255) + (x >> 8);
// At this point, x will be in the range: 0 <= x < 256.
// If the answer 0, x could potentially be 255 which is not fully reduced.
// Here's an ugly way of implementing: if (x == 255) x -= 255;
// (See comments for a simpler version by Paul R.)
unsigned int t = (x + 1) >> 8;
t = !t + 0xffffffff;
t &= 255;
x += ~t + 1;
// x = 186
Run Code Online (Sandbox Code Playgroud)
如果unsigned int是32位整数,这将起作用.
编辑:模式应该足够明显,以了解如何将其推广到2^n - 1.您只需要弄清楚需要多少次迭代.对于n = 8和32位整数,4次迭代就足够了.
编辑2:
这是一个稍微更优化的版本与Paul R.的条件减法代码相结合:
unsigned int x = 4023156861;
x = (x & 65535) + (x >> 16); // Reduce to 17 bits
x = (x & 255) + (x >> 8); // Reduce to 9 bits
x = (x & 255) + (x >> 8); // Reduce to 8 bits
x = (x + ((x + 1) >> 8)) & 255; // Reduce to < 255
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1370 次 |
| 最近记录: |