我有一个十六进制的 DWORD 值可能如下所示:
DWORD Val = 0xFF01091A
如何读取每个字节?我的意思是,我如何阅读 FF、01、09 和 1A?
谢谢!
不是真的更像:
uint8_t Byte1 = (Val>> 0) & 0xFF;
uint8_t Byte2 = (Val>> 8) & 0xFF;
uint8_t Byte3 = (Val>>16) & 0xFF;
uint8_t Byte4 = (Val>>24) & 0xFF;
DWORD value;
// casts to `char *` are always ok:
unsigned char * bytes = (unsigned char *)&value;
unsigned char third_byte = bytes[2];
请记住,这将获取放置在内存中的字节:在 little-endian 机器bytes[0]
上将保存最低有效字节,在 big-endian 机器上将保存最高有效字节。
如果您想按重要性获取字节,请按照Efraim 的回答中的建议使用移位。
DWORD x1 = (0xFF01091A & 0xFF000000) >> 24;
DWORD x2 = (0xFF01091A & 0x00FF0000) >> 16;
DWORD x3 = (0xFF01091A & 0x0000FF00) >> 8;
DWORD x4 = (0xFF01091A & 0x000000FF) >> 0;
Use a union:
union Bytes {
char c[4];
unsigned int n;
};
int main() {
Bytes b;
b.n = 0xFF01091A;
char c = b.c[2];
}
Edit: Sorry, this is C++ code. I'm too tired to convert it to C and test it, but you get the idea?
AraK 的方法很有效。另一种方法是:
char x1 = *(((char*)&Val) + 0);
char x2 = *(((char*)&Val) + 1);
char x3 = *(((char*)&Val) + 2);
char x4 = *(((char*)&Val) + 3);
但请注意,这种方式会对机器的字节序敏感。
掩码和移位(如先前答案中所建议)有效;一个有点棘手的替代方案是“指针类型双关语”,即
xlowbyte = (unsigned char*)(&Val) [0]; /* LSB, 0x1A */
xmidlowb = (unsigned char*)(&Val) [1]; /* 2nd-LSB, 0x09 */
etc -- assuming you're on a little-endian machine (which is likely if you use Windows).