gpt4 book ai didi

c - 位域操作缺点

转载 作者:太空宇宙 更新时间:2023-11-04 06:41:35 25 4
gpt4 key购买 nike

我正在阅读这个链接

http://dec.bournemouth.ac.uk/staff/awatson/micro/articles/9907feat2.htm

我无法从链接中理解以下语句,请帮助我理解这一点。

The programmer just writes some macros that shift or mask the appropriate bits to get what is desired. However, if the data involves longer binary encoded records, the C API runs into a problem. I have, over the years, seen many lengthy, complex binary records described with the short or long integer bit-field definition facilities. C limits these bit fields to subfields of integer-defined variables, which implies two limitations: first of all, that bit fields may be no wider, in bits, than the underlying variable; and secondly, that no bit field should overlap the underlying variable boundaries. Complex records are usually composed of several contiguous long integers populated with bit-subfield definitions.

ANSI-compliant compilers are free to impose these size and alignment restrictions and to specify, in an implementation-dependent but predictable way, how bit fields are packed into the underlying machine word structure. Structure memory alignment often isn’t portable, but bit field memory is even less so.

我从这些陈述中了解到,宏可用于屏蔽向左或向右移位的位。但是我心里有一个疑问,为什么他们要使用宏? - 我认为通过在宏中定义它,无论是 16 位还是 32 位操作系统,都可以建立可移植性。是真的吗?我无法理解上述声明中提到的两个缺点。1.bit 字段可能不会更宽2.任何位域都不应与底层变量边界重叠

和线,

Complex records are usually composed of several contiguous long integers populated with bit-subfield definitions.

最佳答案

1.bit 字段可能不会更宽

假设您想要一个 200 位长的位域。

struct my_struct {
int my_field:200; /* Illegal! No integer type has 200 bits --> compile error!
} v;

2.任何位域都不应与底层变量边界重叠

假设您需要两个 30 位位域,并且编译器使用 32 位整数作为基础变量。

struct my_struct {
unsigned int my_field1:30;
unsigned int my_field2:30; /* Without padding this field will overlap a 32-bit boundary */
} v;

通常,编译器会自动添加填充,生成具有以下布局的结构:

struct my_struct {
unsigned int my_field1:30;
:2 /* padding added by the compiler */
unsigned int my_field2:30; /* Without padding this field will overlap a 32-bit boundary */
:2 /* padding added by the compiler */
} v;

关于c - 位域操作缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7386657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com