wonderer
wonderer

Reputation: 3557

parsing bytes (C Windows)

I have a DWORD value that in Hex might look like:

DWORD Val = 0xFF01091A

How can I read each byte? What I mean is, how can I read FF, 01, 09 and 1A?

Thanks!

Upvotes: 3

Views: 1620

Answers (6)

anon
anon

Reputation:

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?

Upvotes: 2

Christoph
Christoph

Reputation: 169713

DWORD value;
// casts to `char *` are always ok:
unsigned char * bytes = (unsigned char *)&value;
unsigned char third_byte = bytes[2];

Keep in mind that this will get the bytes as they are placed in memory: On little-endian machines bytes[0] will hold the least significant byte, on big-endian machines it'll hold the most significant one.

If you want to get the bytes by significance, use shifting as suggested in Efraim's answer.

Upvotes: 5

Khaled Alshaya
Khaled Alshaya

Reputation: 96889

DWORD x1 = (0xFF01091A & 0xFF000000) >> 24;
DWORD x2 = (0xFF01091A & 0x00FF0000) >> 16;
DWORD x3 = (0xFF01091A & 0x0000FF00) >> 8;
DWORD x4 = (0xFF01091A & 0x000000FF) >> 0;

Upvotes: 2

EFraim
EFraim

Reputation: 13038

Not really its more like:

uint8_t Byte1 = (Val>> 0) & 0xFF;
uint8_t Byte2 = (Val>> 8) & 0xFF;
uint8_t Byte3 = (Val>>16) & 0xFF;
uint8_t Byte4 = (Val>>24) & 0xFF;

Upvotes: 8

Alex Martelli
Alex Martelli

Reputation: 882481

Mask and shift (as suggested in a previous answer) works; a somewhat trickier alternative is "pointer type punning", i.e.

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

Upvotes: 1

Kennet Belenky
Kennet Belenky

Reputation: 2753

AraK's way works. An other way you can do it is:

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

Watch out though, this way will be sensitive to the endian-ness of the machine.

Upvotes: 1

Related Questions