3

我有一个十六进制的 DWORD 值可能如下所示:

DWORD Val = 0xFF01091A

如何读取每个字节?我的意思是,我如何阅读 FF、01、09 和 1A?

谢谢!

4

6 回答 6

8

不是真的更像:

uint8_t Byte1 = (Val>> 0) & 0xFF;
uint8_t Byte2 = (Val>> 8) & 0xFF;
uint8_t Byte3 = (Val>>16) & 0xFF;
uint8_t Byte4 = (Val>>24) & 0xFF;
于 2009-07-24T20:12:43.827 回答
5
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 的回答中的建议使用移位。

于 2009-07-24T20:11:27.870 回答
2
DWORD x1 = (0xFF01091A & 0xFF000000) >> 24;
DWORD x2 = (0xFF01091A & 0x00FF0000) >> 16;
DWORD x3 = (0xFF01091A & 0x0000FF00) >> 8;
DWORD x4 = (0xFF01091A & 0x000000FF) >> 0;
于 2009-07-24T20:03:40.537 回答
2

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?

于 2009-07-24T20:15:51.077 回答
1

AraK 的方法很有效。另一种方法是:

char x1 = *(((char*)&Val) + 0);
char x2 = *(((char*)&Val) + 1);
char x3 = *(((char*)&Val) + 2);
char x4 = *(((char*)&Val) + 3);

但请注意,这种方式会对机器的字节序敏感。

于 2009-07-24T20:11:56.230 回答
1

掩码和移位(如先前答案中所建议)有效;一个有点棘手的替代方案是“指针类型双关语”,即

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

于 2009-07-24T20:13:12.500 回答