关闭

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

549人阅读 评论(2) 收藏 举报
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;
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:319640次
    • 积分:2861
    • 等级:
    • 排名:第12466名
    • 原创:27篇
    • 转载:113篇
    • 译文:0篇
    • 评论:26条
    最新评论