cpx
cpx

Reputation: 17577

DWORD to bytes using bitwise shift operators

I can't get it to work correctly.

#include <windows.h>

int main()
{
    DWORD i  = 6521;

    BYTE first = i >> 32;
    BYTE second = i >> 24;
    BYTE third = i >> 16;
    BYTE fourth = i >> 8;

    i = (((DWORD)fourth) << 24) | (((DWORD)third) << 16) | (((DWORD)second) << 8) | first;
}

Upvotes: 2

Views: 8409

Answers (4)

Michael Dorgan
Michael Dorgan

Reputation: 12515

Your shifts are not quite correct.


BYTE first  = i         >> 24;
BYTE second = i <<  8   >> 24;
BYTE third  = i <<  16  >> 24;
BYTE fourth = i <<  24  >> 24;

What I am doing is shifting down 24 for the top byte, then shifting up in increments of 8 to clear the top bits and place the next byte in position for the shift down.

You could read the value at dword as a byte array (or struct) of 4 bytes to do this as well and let the compile do the work for you.

Upvotes: 2

Jay
Jay

Reputation: 14481

The bytes aren't always in the order that you expect, though Neil's solution is correct. You probably want to look at "endianess" if you're having that problem

Upvotes: 1

Maciej Hehl
Maciej Hehl

Reputation: 7995

I think You shift Your DWORD too much. By 8 bits too much :)

Upvotes: 2

anon
anon

Reputation:

BYTE first = (i >> 24) & 0xff;
BYTE second = (i >> 16) & 0xff;
BYTE third = (i >> 8) & 0xff;
BYTE fourth = i & 0xff ;

Upvotes: 15

Related Questions