与C语言一样,C++也允许指定占用特定位数的结构成员,这使得创建与某个硬件设备上的寄存器对应的数据结构非常方便。字段的类型应为整形或枚举,接下来是冒号,冒号后面是一个数字,它指定了使用的位数。可以使用没有名称的字段来提供间距。每个成员都被称为位字段。下面是一个例子:
struct torgle_register
{
unsigned int SN : 4; // 4bit for SN value
unsigned int : 4; // 4bit unused
bool goodIn : 1; // valid input (1 bit)
bool goodTorgle : 1; // successful torgling
};
可以像通常那样初始化这些字段,还可以使用标准的结构表示法来访问位字段:
torgle_register tr = {14, true, false};
代码:
#include <stdio.h>
#include <iostream>
#pragma pack(1)
struct test_register1
{
unsigned int SM0 : 4;
unsigned int SM1 : 4;
unsigned int SM2 : 4;
unsigned int SM3 : 4;
unsigned int SM4 : 4;
unsigned int SM5 : 4;
unsigned int SM6 : 4;
unsigned int SM7 : 4;
bool SN0 : 1;
bool SN1 : 1;
bool SN2 : 1;
bool SN3 : 1;
bool SN4 : 1;
bool SN5 : 1;
bool SN6 : 1;
bool SN7 : 1;
};
struct test_register2
{
unsigned int SM0 : 4;
unsigned int SM1 : 4;
unsigned int SM2 : 4;
unsigned int SM3 : 4;
unsigned int SM4 : 4;
unsigned int SM5 : 4;
unsigned int SM6 : 4;
unsigned int SM7 : 4;
unsigned int SM8 : 4;
bool SN0 : 1;
bool SN1 : 1;
bool SN2 : 1;
bool SN3 : 1;
bool SN4 : 1;
bool SN5 : 1;
bool SN6 : 1;
bool SN7 : 1;
};
struct test_register3
{
unsigned int SM0 : 4;
unsigned int SM1 : 4;
unsigned int SM2 : 4;
unsigned int SM3 : 4;
unsigned int SM4 : 4;
unsigned int SM5 : 4;
unsigned int SM6 : 4;
unsigned int SM7 : 4;
unsigned int SM8 : 4;
bool SN0 : 1;
bool SN1 : 1;
bool SN2 : 1;
bool SN3 : 1;
bool SN4 : 1;
bool SN5 : 1;
bool SN6 : 1;
bool SN7 : 1;
bool SN8 : 1;
};
int main()
{
int size1 = sizeof(test_register1);
int size2 = sizeof(test_register2);
int size3 = sizeof(test_register3);
}
size1 = 5;
size2 = 9;
size3 = 10;
#include <stdio.h>
#include <iostream>
#pragma pack(4)
struct test_register1
{
unsigned int SM0 : 4;
unsigned int SM1 : 4;
unsigned int SM2 : 4;
unsigned int SM3 : 4;
unsigned int SM4 : 4;
unsigned int SM5 : 4;
unsigned int SM6 : 4;
unsigned int SM7 : 4;
bool SN0 : 1;
bool SN1 : 1;
bool SN2 : 1;
bool SN3 : 1;
bool SN4 : 1;
bool SN5 : 1;
bool SN6 : 1;
bool SN7 : 1;
};
struct test_register2
{
unsigned int SM0 : 4;
unsigned int SM1 : 4;
unsigned int SM2 : 4;
unsigned int SM3 : 4;
unsigned int SM4 : 4;
unsigned int SM5 : 4;
unsigned int SM6 : 4;
unsigned int SM7 : 4;
unsigned int SM8 : 4;
bool SN0 : 1;
bool SN1 : 1;
bool SN2 : 1;
bool SN3 : 1;
bool SN4 : 1;
bool SN5 : 1;
bool SN6 : 1;
bool SN7 : 1;
};
struct test_register3
{
unsigned int SM0 : 4;
unsigned int SM1 : 4;
unsigned int SM2 : 4;
unsigned int SM3 : 4;
unsigned int SM4 : 4;
unsigned int SM5 : 4;
unsigned int SM6 : 4;
unsigned int SM7 : 4;
unsigned int SM8 : 4;
bool SN0 : 1;
bool SN1 : 1;
bool SN2 : 1;
bool SN3 : 1;
bool SN4 : 1;
bool SN5 : 1;
bool SN6 : 1;
bool SN7 : 1;
bool SN8 : 1;
};
int main()
{
int size1 = sizeof(test_register1);
int size2 = sizeof(test_register2);
int size3 = sizeof(test_register3);
}
size1=8
size2=12
size3=12
字节对齐不一样的情况下结构体的大小也不一样。