在DWORD中设置特定的字节

Set specific byte in DWORD

本文关键字:字节 设置 DWORD      更新时间:2023-10-16

如何在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,如果我理解正确的话-我可以使用next宏:

#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)

?

试试这些宏:

#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是不够的。
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) ) );