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

标签 c math video bit-manipulation modulus

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

method I came up with 看起来不是很优雅或快速

int non_smaller_int_divisible_by_16(int x)
{
  return x + ((16 - (x % 16)) % 16);
}

预期的结果是

result | X values
-------|----------
16     | 1,2,..., 16
32     | 17, 18, ... 32
48     | 33, 34, ..., 48

等等

最佳答案

int non_smaller_int_divisible_by_16(int x)
{
  return (x + 15) & ~15;
}

由于 16 是 2 的幂,您可以使用二进制掩码 - 加 15 以便我们得到下一个最高倍数,并使用 15 的按位取反进行掩码,以清除底部位。

编辑:

不清楚您希望负数发生什么 - 您和我的代码都将四舍五入到更正的值(即负数会变小)。如果负值在您的程序中没有意义,最好使用无符号类型。

最后,你可能有兴趣看看Bit Twiddling Hacks ,这是一个很好的集合,其中包含一些非常聪明(如果通常非​​常晦涩)的技巧。

关于c - 快速增加数字为 C 中的 mod 16,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6244036/

相关文章:

algorithm - 变半径圆覆盖算法

python - 从 N*N*N 到 N 的双射函数

android - 将缩略图设置为 VideoView 的 Intent

在等距投影中将 3D 坐标转换为 2D

c - 有没有办法在 AVR gcc 中为引脚定义宏,以便我可以将它们作为变量访问?

c - 是否需要保留填充位?

objective-c - 将浮点指针数组传递到 VBO

java - Android URI 错误 java.io.FileNotFoundException : No content provider: http://

android - FFmpeg 测试演示中的 java.lang.ExceptionInInitializerError

C静态变量