cwinapitypesdword

DWORD variable with low/high word and low/high byte


How in C can we read and make DWORD variables with a low and high word and low and high byte?


Solution

  • In Win32 a DWORD is a 32 bit unsigned integer. In other contexts it could possibly mean something else.

    Assuminng the Win32 definition (and other Win32 typedefs):

    BYTE lsb = 0x11 :
    BYTE next_lsb = 0x22 :
    BYTE next_msb = 0x33 :
    BYTE msb = 0x44 :
    
    DWORD dword_from_bytes = (msb << 24) | (next_msb << 16) | (next_lsb << 8) | lsb ;
    

    dword_from_bytes will have the value 0x44332211.

    Similarly:

    WORD lsw = 0x1111 :
    WORD msw = 0x2222 :
    
    DWORD dword_from_words = (msw << 16) | lsw ;
    

    dword_from_words will have the value 0x22221111.

    To extract say the third byte from dword_from_bytes for example:

    next_msb = (dword_from_bytes >> 16) & 0xff ;
    

    although the & 0xff is not strictly necessary in this case given the type of next_msb, but if the type of the receiver were larger than 8 bits, it will mask off the msb bits.