ao929929fei的专栏

站在高处看世界

C语言struct和union结合使用,空间最小

struct StUserData 
{
	unsigned userdata1 : 1;		// 0--		1--
	unsigned userdata2 : 2;		// 0--    1--    2--   3--
	unsigned userdata3 : 3;
	unsigned userdata4 : 4;

	unsigned normaldata1 : 1;
	unsigned normaldata2 : 2;
	unsigned normaldata3 : 3;
	unsigned normaldata4 : 4;

	unsigned otherdata1 : 3;
	unsigned otherdata2 : 3;
	unsigned otherdata3 : 3;
	unsigned otherdata4 : 3;
};

union UnUserData
{
	StUserData info;
	UINT32 data;
};

int _tmain(int argc, _TCHAR* argv[])
{
	UnUserData data;
	memset(&(data.info), 0, sizeof(data.info));

	data.info.userdata1 = 1;
	data.info.userdata2 = 3;
	data.info.userdata3 = 5;
	data.info.userdata4 = 7;

	data.info.normaldata1 = 0;
	data.info.normaldata2 = 3;
	data.info.normaldata3 = 5;
	data.info.normaldata4 = 7;

	data.info.otherdata1 = 0;
	data.info.otherdata2 = 2;
	data.info.otherdata3 = 4;
	data.info.otherdata4 = 6;

	UnUserData data2;
	data2.data = data.data;
	return 0;
}

阅读更多
文章标签: struct 语言 c
个人分类: 编程技巧与实现
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭