DWORD变量,带低/高字和低/高字节

时间:2010-11-21 11:47:55

标签: c winapi types dword

在C中我们如何读取和生成具有低字和高字以及低字节和高字节的DWORD变量?

3 个答案:

答案 0 :(得分:6)

WinAPI为这些类型的操作提供了宏,例如:

答案 1 :(得分:2)

在Win32中,DWORD是32位无符号整数。在其他情况下,它可能意味着别的东西。

说明Win32定义(以及其他Win32 typedef):

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的值为0x44332211

类似地:

WORD lsw = 0x1111 :
WORD msw = 0x2222 :

DWORD dword_from_words = (msw << 16) | lsw ;

dword_from_words的值为0x22221111

例如从<{1}}中提取第三个字节:

dword_from_bytes

虽然next_msb = (dword_from_bytes >> 16) & 0xff ; 在这种情况下并不是绝对必要的,但是如果接收器的类型大于8位,它将掩盖msb位。

答案 2 :(得分:0)

#include <stdint.h>
#include <stdio.h>

typedef union _little_endian{
    struct _word{
        union _msw{
            struct _msw_byte{
                uint8_t MSB;
                uint8_t LSB;
            } __attribute__((__packed__)) MSW_BYTE;
            uint16_t WORD;
        } MSW;
        union _lsw{
            struct _lsw_byte{
                uint8_t MSB;
                uint8_t LSB;
            } __attribute__((__packed__)) LSW_BYTE;
            uint16_t WORD;
        } LSW;
    } __attribute__((__packed__)) WORD;
    uint32_t DWORD;
} DWORD;

int main(int argc, char *argv[]){
    DWORD test1;
    test1.WORD.MSW.MSW_BYTE.MSB = 1;
    test1.WORD.MSW.MSW_BYTE.LSB = 2;
    test1.WORD.LSW.LSW_BYTE.MSB = 3;
    test1.WORD.LSW.LSW_BYTE.LSB = 4;
    printf("test1: hex=%x uint=%u\n", test1.DWORD, test1.DWORD);
    
    DWORD test2;
    test2.DWORD = 0x08080404;
    printf("test2: hex=%x uint=%u\n", test2.DWORD, test2.DWORD);
    printf("test2.WORD.MSW.MSW_BYTE.MSB: uint=%u\n", test2.WORD.MSW.MSW_BYTE.MSB);
    printf("test2.WORD.MSW.MSW_BYTE.LSB: uint=%u\n", test2.WORD.MSW.MSW_BYTE.LSB);
    printf("test2.WORD.LSW.LSW_BYTE.MSB: uint=%u\n", test2.WORD.LSW.LSW_BYTE.MSB);
    printf("test2.WORD.LSW.LSW_BYTE.LSB: uint=%u\n", test2.WORD.LSW.LSW_BYTE.LSB);
    
    return 0;
}

我更喜欢结合使用结构和联合。

输出:

test1: hex=4030201 uint=67305985
test2: hex=8080404 uint=134743044
test2.WORD.MSW.MSW_BYTE.MSB: uint=4
test2.WORD.MSW.MSW_BYTE.LSB: uint=4
test2.WORD.LSW.LSW_BYTE.MSB: uint=8
test2.WORD.LSW.LSW_BYTE.LSB: uint=8