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

对于unsigned int x,是否可以仅使用以下运算符(加上没有循环,分支或函数调用)来计算x%255(或者通常为2 ^ n – 1)?

!~&^|+<<>>

是的,这是可能的。 对于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 

只需创建一个包含所有值的数组(只需要32或64个条目(即128或512字节)。然后只需查看即可。

当然。 只需拿出一本旧的计算机体系结构教科书,就可以在布尔代数上刷新内存。 CPU的ALU使用AND和OR进行操作; 你也可以。

但为什么?

学术演习? 家庭作业? 好奇?