3

我们如何在 C 语言中读取和制作DWORD具有低位和高位字以及低位和高位字节的变量?

4

3 回答 3

8

WinAPI provides macros for the manipulations of these types, such as:

于 2010-11-21T12:18:20.223 回答
3

在 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

例如,要提取第三个字节dword_from_bytes

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

尽管& 0xff在这种情况下,考虑到 的类型,这并不是绝对必要的next_msb,但如果接收器的类型大于 8 位,它将屏蔽掉 msb 位。

于 2010-11-21T12:14:42.403 回答
1
#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
于 2020-10-12T13:15:55.253 回答