快速增加数字为C中的mod 16

Avi*_*hek 4 c math video bit-manipulation modulus

获得可被16整除的最近,非小数字的最佳方法是什么?

我提出方法看起来并不优雅或快速

int non_smaller_int_divisible_by_16(int x)
{
  return x + ((16 - (x % 16)) % 16);
}
Run Code Online (Sandbox Code Playgroud)

预期的结果是

result | X values
-------|----------
16     | 1,2,..., 16
32     | 17, 18, ... 32
48     | 33, 34, ..., 48
Run Code Online (Sandbox Code Playgroud)

等等

Joh*_*ter 11

int non_smaller_int_divisible_by_16(int x)
{
  return (x + 15) & ~15;
}
Run Code Online (Sandbox Code Playgroud)

由于16是2的幂,你可以使用二进制掩码 - 加15,这样我们得到下一个最高倍数,并用15的按位反转掩码,以清除底部位.

编辑:

目前尚不清楚你想用负数发生什么 - 你和我的代码都将转向更正的值(即负数会变小).如果负值在程序中没有意义,那么最好使用无符号类型.

最后,你可能有兴趣看看Bit Twiddling Hacks,这是一些非常聪明(如果经常是非常模糊)的技巧.


Dav*_*nan 5

@herehere的解决方案更优雅,更快,但如果您需要使用不是2的幂的数字,那么您可以使用此方法.

int non_smaller_int_divisible_by_n(int x, int n)
{
  return n*((x+n-1)/n);
}
Run Code Online (Sandbox Code Playgroud)

  • 实际上,如果你声明所有内容都是"无符号"并且使编译时间保持不变,那么GCC(至少)会为bit-twiddling版本生成相同的代码.由于您的表格更清晰,更通用,因此最好...... (3认同)