测试是否在DWORD标志中设置了特定的位

Testing whether specific bits are set in a DWORD flag

本文关键字:设置 是否 DWORD 标志 测试      更新时间:2023-10-16

我有一个DWORD变量&我想测试其中是否设置了特定的位。我下面有我的代码,但我不确定我是否从win32数据类型KBDLLHOOKSTRUCT传输到我的lparam数据类型正确?

请参阅MSDN文档DWORD标志变量:http://msdn.microsoft.com/en-us/library/ms644967(v=vs.85).aspx

union KeyState 
{
    LPARAM lparam;      
    struct     
    {         
        unsigned nRepeatCount : 16;         
        unsigned nScanCode    : 8;         
        unsigned nExtended    : 1;         
        unsigned nReserved    : 4;         
        unsigned nContext     : 1;         
        unsigned nPrev        : 1;         
        unsigned nTrans       : 1;     
    }; 
}; 

KBDLLHOOKSTRUCT keyInfo = *((KBDLLHOOKSTRUCT*)lParam);
KeyState myParam;
myParam.nRepeatCount    = 1;
myParam.nScanCode       = keyInfo.scanCode;
myParam.nExtended       = keyInfo.flags && LLKHF_EXTENDED; // maybe it should be keyInfo.flags & LLKHF_EXTENDED or keyInfo.flags >> LLKHF_EXTENDED
myParam.nReserved       = 0;        
myParam.nContext        = keyInfo.flags && LLKHF_ALTDOWN;     
myParam.nPrev           = 0; // can store the last key pressed as virtual key/code, then check against this one, if its the same then set this to 1 else do 0   
myParam.nTrans          = keyInfo.flags && LLKHF_UP;

// Or maybe I shd do this to transfer bits...
myParam.nRepeatCount    = 1;
myParam.nScanCode       = keyInfo.scanCode;
myParam.nExtended       = keyInfo.flags & 0x01;
myParam.nReserved       = (keyInfo.flags >> 0x01) & (1<<3)-1;      
myParam.nContext        = keyInfo.flags & 0x05;     
myParam.nPrev           = 0;       // can store the last key pressed as virtual key/code, then check against this one, if its the same then set this to 1 else do 0   
myParam.nTrans          = keyInfo.flags & 0x07;

而不是

myParam.nExtended = keyInfo.flags && LLKHF_EXTENDED
你需要

myParam.nExtended = (keyInfo.flags & LLKHF_EXTENDED) != 0;

&而不是&&,因为您想要按位的而不是逻辑的!=0确保答案是0或1(而不是0或其他非零值),因此它可以在您的一位位域中表示。

CheckBits(DWORD var, DWORD mask)
{
    DWORD setbits=var&mask; //Find all bits are set
    DWORD diffbits=setbits^mask; //Find all set bits that differ from mask
    return diffbits!=0; //Retrun True if all specific bits in variable are set
}

如果您想合并两个位,您将使用 | (位或)运算符:

myParam.nExtended = keyInfo.flags | LLKHF_EXTENDED;

myParam.nExtended = keyInfo.flags | 0x01;

检查bit是否设置了,可以使用 & (bitwise AND)运算符:

if(myParam.nExtended & LLKHF_EXTENDED) ...