简体   繁体   中英

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;
}
BYTE first = (i >> 24) & 0xff;
BYTE second = (i >> 16) & 0xff;
BYTE third = (i >> 8) & 0xff;
BYTE fourth = i & 0xff ;

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM