本文介绍了C快速计算下一个4的倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将无符号int
舍入为4
倍数的快速方法是什么?
What's a fast way to round up an unsigned int
to a multiple of 4
?
4的倍数具有两个最低有效位0,对吗?所以我可以将它们屏蔽掉,然后执行switch语句,将1,2或3添加到给定的uint
.
A multiple of 4 has the two least significant bits 0, right? So I could mask them out and then do a switch statement, adding either 1,2 or 3 to the given uint
.
这不是一个非常优雅的解决方案.
That's not a very elegant solution..
还有算术综述:
myint == 0 ? 0 : ((myint+3)/4)*4
也许有更好的方法进行一些位操作?
Probably there's a better way including some bit operations?
推荐答案
(myint + 3) & ~0x03
3的加法使得4的下一个倍数成为4的上一个倍数,这是通过模运算产生的,因为除数是2的幂,所以可以通过掩膜实现.
The addition of 3 is so that the next multiple of 4 becomes previous multiple of 4, which is produced by a modulo operation, doable by masking since the divisor is a power of 2.
这篇关于C快速计算下一个4的倍数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!