将数字向上舍入到 int 大小边界字节数的方法
以下代码将参数四舍五入为 int 大小边界字节数。
#define _INTSIZE(n) ((sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1))
在我的机器上,int 是 4 个字节,所以——如果我错了,请纠正我——这应该与查找整数的下一个 4 的倍数(在我的机器上)相同。对于下一个 4 的倍数,我的意思是,如果该数字不是 4 的倍数,则应将其向上舍入为 4 的倍数。如果已经是 4 的倍数,则应将其保留。
我一直在玩这个代码。它的长处和短处是:为什么这段代码有效?(也许它不起作用,但似乎有效。)我想有一些理由认为它适用于所有情况,而不仅仅是我尝试过的那些。
The following code rounds up the argument to an int size boundary number of bytes.
#define _INTSIZE(n) ((sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1))
On my machine int is 4 bytes, so -- correct me if I'm wrong -- this should be the same as looking for the next multiple of 4 of an integer (on my machine). By next multiple of 4, I mean the number should be rounded up to a multiple of 4 if not a multiple of 4. If already a multiple of 4, it should be left alone.
I've been playing around with this code. The long and short of it is: why does this code work? (Maybe it doesn't, but it seems to.) I would like some reason to think it will work for ALL cases, not just the ones I've tried out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该代码首先将数字加三。
然后它将最后两位清零以向下舍入为四的倍数。就像您可以通过用零替换最后两位数字来向下舍入到最接近的十进制 100 的倍数一样。)
如果该数字已经是四的倍数,则向其添加 3,然后向下舍入到最接近的四的倍数独自一人,随心所欲。如果该数字比 4 的倍数大 1、2 或 3,则向其添加 3 会使其高于下一个 4 的倍数,然后向下舍入到该数字,完全按照需要进行。
The code first adds three to the number.
Then it zeroes out the last two bits to round down to a multiple of fours. Just like you can round down to the nearest multiple of 100 in decimal by replacing the last two digits with zeroes.)
If the number is already a multiple of four, adding three to it and then rounding down to the nearest multiple of four leaves it alone, as desired. If the number is 1, 2, or 3 more than a multiple of 4, adding 3 to it raises it above the next multiple of 4, which it then rounds down to, exactly as desired.
这实际上有一个微妙的错误。 '& ~(sizeof(int) - 1)' 仅当 sizeof(int) 是 2 的幂、36 位和 80 位架构等确实存在时才有效。如果将其更改为 '% sizeof(int)' 那么它将始终是正确的。
There is actually a subtle bug in this. the '& ~(sizeof(int) - 1)' only works if sizeof(int) is a power of two, 36 bit and 80 bit architectures among others do exist. if you change it to '% sizeof(int)' then it will always be correct.