是否可以将 C 中的结构打包为由位定义的大小
我有以下结构
struct header {
unsigned int op:16;
unsigned int A:1;
unsigned int B:1;
unsigned int C:1;
unsigned int pad:1;
}
int main() {
struct header a;
printf("size of header is: %lu\n", sizeof(a));
return 0;
}
输出是标头的大小是:4
如果我使用__attribute__((__packed__))
struct __attribute__((__packed__)) header {
unsigned int op:16;
unsigned int A:1;
unsigned int B:1;
unsigned int C:1;
unsigned int pad:1;
}
int main() {
struct header a;
printf("size of header is: %lu\n", sizeof(a));
return 0;
}
输出是标头的大小是:3
有没有办法避免填充到 3 个字节?我可以只取所需的 20 位吗? 我需要这个的原因之一是将结构转换为十六进制数字,例如
struct header test1, test2;
test1.op = 1;
test1.A = 0;
test1.B = 1
test1.C = 0;
test1.pad = 0;
test2.op = 1024;
test2.A = 0;
test2.B = 1
test2.C = 1;
test2.pad = 0;
分别转换为 0x20001
和 0x60400
并且希望避免需要删除填充,如果可能的
I have the following struct
struct header {
unsigned int op:16;
unsigned int A:1;
unsigned int B:1;
unsigned int C:1;
unsigned int pad:1;
}
int main() {
struct header a;
printf("size of header is: %lu\n", sizeof(a));
return 0;
}
output is size of header is: 4
If I use __attribute__((__packed__))
struct __attribute__((__packed__)) header {
unsigned int op:16;
unsigned int A:1;
unsigned int B:1;
unsigned int C:1;
unsigned int pad:1;
}
int main() {
struct header a;
printf("size of header is: %lu\n", sizeof(a));
return 0;
}
output is size of header is: 3
Is there a way to avoid the padding to 3 bytes? Can I take only the required 20 bits?
One of the reason I need this is for converting the struct to a hex number e.g
struct header test1, test2;
test1.op = 1;
test1.A = 0;
test1.B = 1
test1.C = 0;
test1.pad = 0;
test2.op = 1024;
test2.A = 0;
test2.B = 1
test2.C = 1;
test2.pad = 0;
is converted to 0x20001
and 0x60400
respectively and would like to avoid the need to remove the padding if possible
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
?
不。
不。
最小可寻址单元是字节。 C 中的所有内容都必须是字节的倍数。
(理论上,您可以使用具有 10 位字节的编译器(或重新编译 GCC),那么您的结构将恰好占用 2 个字节。这将是乏味的、不可移植的,我会说荒谬)。然而,在任何现代平台上,一个字节都有 8 位。
No.
No.
No.
The smallest addressable unit is a byte. Everything in C has to be a multiple of a byte.
(Theoretically, you could use a compiler (or re-compile GCC) with a byte having 10 bits, then your struct would take exactly 2 bytes. That would be tedious, non-portable and I would say ridiculous). However, on any modern platform, a byte has 8 bits.
C 2018 6.2.6 2 说:
因此,一个结构体,即使它仅由位域组成,也不是位域,它必须由整数个组成字节。
(AC 实现可以通过允许某些对象为小数字节来扩展 C 标准,但我不知道有任何 C 实现可以做到这一点。)
C 2018 6.2.6 2 says:
Therefore, a structure, which is not a bit-field even if it is composed solely of bit-fields, must be composed of a whole number of bytes.
(A C implementation could extend the C standard by allowing some objects to be a fractional number of bytes, but I am not aware of any C implementation that does this.)