union存取低高位
联合体类型,变量成员共用同一内存,同一时刻只能保存一个成员的数据。
以1个4字节数据,传递r\g\b为例
#include<stdint.h> #include<iostream> int main() { uint32_t myV; //用于模拟值传递 //写 { union { struct { uint32_t r : 8; //注意与“要传递的值”同类型,防止新开辟1个字节造成的位不连续 uint32_t g : 8; uint32_t b : 8; }_s; uint32_t v = 0; //要传递的值 }_u; _u._s.r = 120; _u._s.g = 130; _u._s.b = 140; std::cout << _u.v << std::endl; myV = _u.v; } //读 { union { struct { uint32_t myR : 8; uint32_t myG : 8; uint32_t myB : 8; }myS; uint32_t rgb = 0; }myU; //模拟值传递 myU.rgb = myV; //获取r\g\b unsigned char r1 = myU.myS.myR; unsigned char g1 = myU.myS.myG; unsigned char b1 = myU.myS.myB; std::cout << (int)r1 << " " << (int)g1 << " " << (int)b1 << std::endl; } }