#include<iostream>
//帮助理解一些关于位段的概念
//下面这个结构相当于
//----int-4bytes-------
//----char-1byte-------
//----char-1byte------- this byte is used as 高字节->低字节 |0(1bits not be used)||f4(3bits)|f3(2bits)|f2(1bits)|f1(1bits)|
//这个结构占据的字节数是8字节,
// int 4
// char 1 pad2 | char1 pad 2
int main()
{
using namespace std;
struct table_entry
{
int count;
char c;
char f1:1;
char f2:1;
char f3:2;
char f4:3;
};
table_entry num = {4,'a',0,1,3,6};
cout<<"f1: "<<num.f1<<endl;
//cout<<"f2: "<<num.f2<<endl;
cout<<"size of this struct is : "<<sizeof(table_entry)<<endl;
cin.get();
return 0;
}
///
/*
int main()
{
using namespace std;
struct table_entry
{
int count;
char c;
unsinged int f1:1;
unsinged int f2:1;
};
table_entry num = {4,'a',0,1};
cout<<"f1: "<<num.f1<<endl;
//cout<<"f2: "<<num.f2<<endl;
cout<<"size of this struct is : "<<sizeof(table_entry)<<endl;
cin.get();
return 0;
}
*/
//这种情况下,结构体占用的字节数是12bytes。
/*
int main()
{
using namespace std;
struct table_entry
{
int count;
unsinged int f1:1;//用掉一个int的长度,
char c;
unsinged int f2:1;//用掉一个int的长度
};
table_entry num = {4,0,'a',1};
cout<<"f1: "<<num.f1<<endl;
//cout<<"f2: "<<num.f2<<endl;
cout<<"size of this struct is : "<<sizeof(table_entry)<<endl;
cin.get();
return 0;
}
*/
//这种情况下,结构体占用的字节数是16bytes。
//另外位段还可以用无名位段进行字节填充类似pad
//比如
// char f1:7; char f2:4;
//char f1:7; char :1;//这个就是无名段, 不能被当做成员来赋值(?)
关于位段的一些理解
猜你喜欢
转载自blog.csdn.net/sy19901011/article/details/35996445
今日推荐
周排行