简体   繁体   English

计算填充字节数的最佳方法是什么

[英]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.

相关问题 计算多组唯一订单数的最佳方法 - Best way to calculate the number of unique orderings of a multiset 无需填充字节即可计算结构大小的函数 - function that calculate Size of Structure without padding bytes C/C++ 将多个字节发送到标准输出的最佳方式 - C/C++ best way to send a number of bytes to stdout fmod十进制数的最佳方法是什么? - What is the best way to fmod a decimal number? 计算多进程程序运行时间的最佳方法是什么? - What is the best way to calculate the running time of a multi-process program? 用套接字传输数据时避免结构填充的最佳方法是什么? - What's the best way to avoid struct padding when transmitting data with a socket? 计算CFStringRef / CFMutableArrayRef使用的字节数 - Calculate the number of bytes used by a CFStringRef / CFMutableArrayRef 在arduino中将两个uint8字节转换为uint16字节的最佳方法是什么? - What is best way to convert two uint8 bytes to uint16 byte in arduino? 在c中分隔运算符和数字的最佳方法是什么 - What's the best way to separate operator and number in c 用C获得整数中最右边的数字的最佳方法是什么? - What is the best way to get right most number in an integer with C?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM