[英]What is the best way to calculate number of padding bytes
What's the most efficient way to calculate the amount of padding for 8-bit data that needs to be a multiple of 32-bit in C? 计算8位数据的填充量的最有效方法是什么,需要是C中32位的倍数?
At the moment I do it like this: 目前我这样做:
pad = (4-size%4)%4;
As long as the optimizing compiler uses bitmasking for the % 4
instead of division, I think your code is probably pretty good. 只要优化编译器对% 4
而不是除法使用位掩码,我认为你的代码可能非常好。 This might be a slight improvement: 这可能会略有改善:
// only the last 2 bits (hence & 3) matter
pad = (4 - (size & 3)) & 3;
But again, the optimizing compiler is probably smart enough to be reducing your code to this anyway. 但同样,优化编译器可能足够聪明,无论如何都要将代码减少到此。 I can't think of anything better. 我想不出更好的事情。
// align n bytes on size boundary
pad n size = (~n + 1) & (size - 1)
this is similar to TypeIA's solution and only machine language ops are used. 这类似于TypeIA的解决方案,只使用机器语言操作。
(~n + 1) computes the negative value, that would make up 0 when added to n
& (size - 1) filters only the last relevant bits.
examples 例子
pad 13 8 = 3
pad 11 4 = 1
pad = (-size)&3;
This should be the fastest. 这应该是最快的。
size 0: pad 0
size 1: pad 3
size 2: pad 2
size 3: pad 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.