解决方法
是的,这是可能的.对于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
如果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