C++/WinAPI - Removing a flag from a DWORD (bitwise operator?)
-
08-07-2021 - |
Question
I now know how to check if there is a certain flag in a DWORD (Specifically a Windows style) by using the bitwise &
AND operator. How would I do this:
if (dwMyFlags & dwSomeFlag) {
// dwMyFlags contains dwSomeFlag
// ->> How do I remove dwSomeFlag from dwMyFlags?
}
I know subtracting it wouldn't work, is there some operator that can remove flags from a DWORD?
Solution
If you know the flag is set you can use exclusive or to unset:
dwMyFlags ^= dwSomeFlag;
If you are unsure of the state of the flag, you need to use bitwise &, and bitwise not ~
dwMyFlags &= ~dwSomeFlag;
OTHER TIPS
Do a bitwise &
with the inverse of the flag that you want:
dwMyFlags = dwMyFlags & ~dwSomeFlag;
You can abbreviate this using &=
:
dwMyFlags &= ~dwSomeFlag;
AND with the bits that are not part of that flag:
dwMyFlags &= ~dwSomeFlag;
This is scalable to removing multiple flags as well:
dwMyFlags &= ~(dwSomeFlag | dwSomeOtherFlag);
Also, Hungarian notation has outlived its use.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow