关于位段的一些理解

#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;//这个就是无名段, 不能被当做成员来赋值(?)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值