在DWORD中设置特定字节

时间:2014-03-29 20:57:32

标签: c++

如何在4字节长度DWORD变量中设置特定字节?

DWORD color_argb;
unsigned char a = 11; // first byte
unsigned char r = 22; // second byte
unsigned char g = 33; // third byte
unsigned char b = 44; // fouth byte

zumalifeguard ,如果我理解正确的话 - 我可以使用下一个宏:

#define SET_COLOR_A(color, a) color |= (a << 24)
#define SET_COLOR_R(color, r) color |= (r << 16)
#define SET_COLOR_G(color, g) color |= (g << 8)
#define SET_COLOR_B(color, b) color |= (b << 0)

2 个答案:

答案 0 :(得分:3)

请尝试使用这些宏:

#define SET_COLOR_A(color, a) color = (DWORD(color) & 0x00FFFFFF) | ((DWORD(a) & 0xFF) << 24)
#define SET_COLOR_R(color, r) color = (DWORD(color) & 0xFF00FFFF) | ((DWORD(r) & 0xFF) << 16)
#define SET_COLOR_G(color, g) color = (DWORD(color) & 0xFFFF00FF) | ((DWORD(g) & 0xFF) << 8)
#define SET_COLOR_B(color, b) color = (DWORD(color) & 0xFFFFFF00) | (DWORD(b) & 0xFF)

重要的是保留未被操作的现有位,而删除正在替换的现有位。如果分配的位置中已存在位,则只需OR&#39}新位。

答案 1 :(得分:2)

DWORD color_argb;
unsigned char a = 11; // first byte
unsigned char r = 22; // second byte
unsigned char g = 33; // third byte
unsigned char b = 44; // fouth byte

color_argb = 0;
int byte_number; // first byte = 1, second byte = 2, etc.

// Set first byte to a;
byte_number = 1;
color_argb |= ( a << (8 * (4 - byte_number) ) );

// Set first byte to a;
byte_number = 2;
color_argb |= ( b << (8 * (4 - byte_number) ) ); 

// Set first byte to a;
byte_number = 3;
color_argb |= ( c << (8 * (4 - byte_number) ) ); 

// Set first byte to a;
byte_number = 4;
color_argb |= ( d << (8 * (4 - byte_number) ) );