Testing whether specific bits are set in a DWORD flag
I have a DWORD variable & I want to test if specific bits are set in it. I have my code below but I am not sure if I am transferring the bits from the win32 data type KBDLLHOOKSTRUCT to my lparam datatype correctly?
See MSDN that documents the DWORD flag variable: 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;
myPa开发者_如何学运维ram.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;
Rather than
myParam.nExtended = keyInfo.flags && LLKHF_EXTENDED
you need
myParam.nExtended = (keyInfo.flags & LLKHF_EXTENDED) != 0;
It's &
not &&
because you want a bitwise and not a logical and. And the !=0
ensures the answer is either 0 or 1 (rather than 0 or some-other-nonzero-value) so it can be represented in your one-bit bitfield.
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
}
If you want to merge two bits, you would use |
(bitwise OR) operator:
myParam.nExtended = keyInfo.flags | LLKHF_EXTENDED;
myParam.nExtended = keyInfo.flags | 0x01;
To check if bit was set, you would use &
(bitwise AND) operator:
if(myParam.nExtended & LLKHF_EXTENDED) ...
精彩评论