是否可以使用按位和受限操作符重写模(2 ^ n – 1)
发布时间:2020-12-16 05:28:35 所属栏目:百科 来源:网络整理
导读:对于unsigned int x,是否可以仅使用以下运算符(加上没有循环,分支或函数调用)来计算x%255(或者一般为2 ^ n-1)? !,?, ^,|,, 解决方法 是的,这是可能的.对于255,可以如下进行: unsigned int x = 4023156861;x = (x 255) + (x 8);x = (x 255) + (x 8);x = (
对于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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |