结构或联合中的'unsigned temp:3'是什么意思?

可能重复:
这个C ++代码是什么意思?

我正在尝试使用JNA将C结构映射到Java。 我遇到了一些我从未见过的东西。

struct定义如下:

 struct op { unsigned op_type:9; //---> what does this mean? unsigned op_opt:1; unsigned op_latefree:1; unsigned op_latefreed:1; unsigned op_attached:1; unsigned op_spare:3; U8 op_flags; U8 op_private; }; 

你可以看到一些变量被定义为unsigned op_attached:1 ,我不确定这是什么意思。 这会影响为这个特定变量分配的字节数吗?

这个结构指定每个字段的长度(以位为单位)。

这个优点是你可以控制sizeof(op) ,如果你小心的话。 结构的大小将是内部字段大小的总和。

在你的情况下,op的大小是32位(即sizeof(op)是4)。

对于每个无符号的xxx:yy组,大小总是四舍五入为8的倍数; 构造。

这意味着:

 struct A { unsigned a: 4; // 4 bits unsigned b: 4; // +4 bits, same group, (4+4 is rounded to 8 bits) unsigned char c; // +8 bits }; // sizeof(A) = 2 (16 bits) struct B { unsigned a: 4; // 4 bits unsigned b: 1; // +1 bit, same group, (4+1 is rounded to 8 bits) unsigned char c; // +8 bits unsigned d: 7; // + 7 bits }; // sizeof(B) = 3 (4+1 rounded to 8 + 8 + 7 = 23, rounded to 24) 

我不确定自己是否记得正确,但我想我说得对。

它声明了一个位域 ; 冒号后面的数字给出了字段的长度(即用多少位来表示它)。

 unsigned op_type:9; 

意思op_type是一个9位的整数变量。

整数类型的冒号修饰符指定int应该占用多少位。