62

可能重复:
这个 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,我不确定这意味着什么。这会影响为这个特定变量分配的字节数吗?

4

4 回答 4

44

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

这样做的好处是你可以控制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)

我不确定我是否记得正确,但我想我没记错。

于 2010-06-01T14:43:51.110 回答
19

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

于 2010-06-01T13:17:51.903 回答
6
unsigned op_type:9;

表示 op_type 是一个 9 位的整数变量。

于 2010-06-01T13:18:24.537 回答
4

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

于 2010-06-01T13:17:53.467 回答