Search code examples
c#bitmaskintptr

Bit masking an IntPtr


How do I use Binary-AND to check if a particular bit is set for an IntPtr object?

I'm calling GetWindowLongPtr32() API to get window style for a window. This function happens to return an IntPtr. I have defined all the flag constants in my program. Now suppose if I want to check whether a particular flag (say WS_VISIBLE) is set, I need to Binary-AND it with my constant, but my constant is of int type, so I cannot do that directly. Try to call ToInt32() and ToInt64() both result in (ArgumentOutOfRangeException) exception. What's my way out?


Solution

  • Just convert IntPtr to an int (it has a conversion operator) and use logical bit operators to test bits.

    const int WS_VISIBLE = 0x10000000;
    int n = (int)myIntPtr;
    if((n & WS_VISIBLE) == WS_VISIBLE) 
        DoSomethingWhenVisible()`