Search code examples
c++bitwise-operators

determine if value contains another value with bitwise operation


I need to compare if a given integral value contains another value using bitwise oprators:

here is example code:

// default flags used by some function
long flags = MB_ICONERROR | MB_YESNOCANCEL;

// here somewhere else in the code, flags value is unknown
// determine if flags contains MB_ICONWARNING
if (flags & MB_ICONWARNING)
    abort(); // flags do not have MB_ICONWARNING, should be false

Above code will hit abort()

MB_ICONERROR is defined as 0x00000010L

MB_ICONWARNING is defined as 0x00000030L

MB_YESNOCANCEL is defined as0x00000003L

I know & operator is used for this but it does not work. I want to evaluate to true if flags contain MB_ICONWARNING, how do I do that?


Solution

  • The messagebox "flag" field is not a pure bitfield, some values are not pure bit-flags, but they are separated into specific bits.

    That means you can't use pure bitwise operations to find out if a value is set or not. You need to mask out the specific bits that contains the value, and the compare against the value you want to check.

    For example, the icon flags seems to be the second nibble (bits 4 to 7), which you get by masking with 0xf0u (the u suffix to make the value an unsigned integer). Then you compare the result of the masking with the icon value you want to check for. For example

    if (flags & 0xf0u == MB_ICONWARNING)
    {
        // The MB_ICONWARNING "flag" is "set"
    }
    

    With the code you have in your question, flags & MB_ICONWARNING, you will get a "true" result both for MB_ICONERROR and MB_ICONWARNING (and any value equal to 0x20.