Union,即聯合體,將幾種數據類型聯合起來的一種數據結構,且共用同一個內存空間。
例如,用24bit表示一個像素點,包含 RED、GREEN、BLUE,每種顏色8bit。使用聯合體便可以定義如下:
typedef union {
struct __attribute__ ((packed)) {
uint8_t r, g, b;
};
uint32_t rgb;
} rgb_color;
上述的union包含了一個結構體和一個無符號整型數據,當需要某一種顏色時可以單獨調用結構體裏面的值;當需要整個像素的值時就可以調用rgb的值。
union的元素共用一個內存空間,其大小以最大的元素所佔的空間爲準。故上圖所示,我們定義的 rgb_color 聯合體佔用 4字節空間。
因爲是佔用的同一個內存空間,所以我們無論修改 rgb 或 r/g/b 的任何值都會同時影響其他的值(小端存儲)。舉個栗子:
#include <stdio.h>
#include <stdlib.h>
typedef unsigned int uint32_t;
typedef unsigned char uint8_t;
typedef union {
struct __attribute__ ((packed)) {
uint8_t r, g, b;
};
uint32_t rgb;
} rgb_color;
void main()
{
rgb_color color;
color.r = 0x12;
color.g = 0x34;
color.b = 0x56;
printf("%x\n", color.r);
printf("%x\n", color.g);
printf("%x\n", color.b);
printf("%x\n", color.rgb);
printf("After re-assign value for g: \n\n");
color.g = 0x78;
printf("%x\n", color.r);
printf("%x\n", color.g);
printf("%x\n", color.b);
printf("%x\n", color.rgb);
printf("After re-aasign value for rgb: \n\n");
color.rgb = 0xabcdefed;
printf("%x\n", color.r);
printf("%x\n", color.g);
printf("%x\n", color.b);
printf("%x\n", color.rgb);
}
代碼執行結果如下:
利用這個特性,可以在數據傳輸時候,對數據進行拆分。比如將一個四字節的int數據(rgb),拆分爲四個無符號字符。
參考資料
C語言之聯合體(union)