C语言中巧用共用体union
使用rgb时经常遇到有的rgb格式是一个整体如0xf032aa
有时候是r=0xf0 ,g=0xee ,b=0xa0.如果要合成一个有的是进行位运算进行合并.
这里我们通过共用体来完成,很节约cpu资源.
废话不多说直接上代码:
#include <stdio.h>
#include <string.h>
typedef union COLOR
{
struct {
unsigned char b; //低
unsigned char g; //中
unsigned char r; //高
};
unsigned int color;
} union_Color;
int main()
{
union_Color c;
c.color=0x0;
c.r=0x12;
c.g=0x34;
c.b=0x56;
printf("%x\n\r",c.color);
return 0;
}
光看代码是比较难理解的,我们通过图片示意出该共用体在内存中的表现形式就可以很容易理解了.