如何用位运算正确判断整数是否包含指定多比特标志位?
Let’s break down why your current approach isn’t working and fix it step by step.
First, the root of the problem lies in how these flags are structured:
- MB_ICONERROR =
0x00000010L(binary:00010000) - MB_ICONWARNING =
0x00000030L(binary:00110000)
When you use if (flags & MB_ICONWARNING), even if flags only has MB_ICONERROR set, the result is 0x10 (non-zero), which evaluates to true in C. That’s why your abort() is triggering incorrectly—because the bitwise AND picks up the overlapping bit between the two flags.
The Proper Check
Since MB_ICONWARNING is a multi-bit value (it requires two bits to be set), you need to verify that all bits of MB_ICONWARNING are present in flags, not just any single overlapping bit. Here’s how to do it:
// 判断flags是否包含MB_ICONWARNING if ((flags & MB_ICONWARNING) == MB_ICONWARNING) { abort(); }
Why This Works
flags & MB_ICONWARNINGisolates the bits in flags that match MB_ICONWARNING.- Comparing the result directly to MB_ICONWARNING ensures that every bit required for MB_ICONWARNING is set in flags. In your example,
flags & MB_ICONWARNINGgives0x10, which doesn’t equal0x30(MB_ICONWARNING), so the condition isfalse—exactly what you want.
Bonus: For Mutually Exclusive Flag Groups
If these icon flags are mutually exclusive (only one can be set at a time, which is common for message box icons), you can also first mask out the entire icon bit range to make the check even clearer:
#define MB_ICON_MASK 0x000000F0L // Covers all MB_ICON* flags if ((flags & MB_ICON_MASK) == MB_ICONWARNING) { abort(); }
This mask strips away unrelated flags (like MB_YESNOCANCEL) and focuses only on the icon bits, making the intent of your code more explicit.
内容的提问来源于stack exchange,提问作者metablaster

