You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用位运算正确判断整数是否包含指定多比特标志位?

Correct Way to Check if Flags Contain MB_ICONWARNING

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_ICONWARNING isolates 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_ICONWARNING gives 0x10, which doesn’t equal 0x30 (MB_ICONWARNING), so the condition is false—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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:20:33