bitfield mask calculation macro

Posted by Aidan Cully on Stack Overflow See other posts from Stack Overflow or by Aidan Cully
Published on 2010-05-04T20:02:08Z Indexed on 2010/05/04 20:08 UTC
Read the original article Hit count: 178

Filed under:
|

We have a set of C macros, here, for using the preprocessor to do bitfield operations, and we run into warnings when attempting to use these macros in visual studio. The problem can be demonstrated very easily:

#define BITFIELD_WIDTHMASK(Width) \
    ((Width) >= 32 ? ~0x0ul : (1ul << (Width)) - 1)

unsigned long foo(void)
{
    return BITFIELD_WIDTHMASK(32);
}

Compiling this with MSVC yields the warning:

test.c(12) : warning C4293: '<<' : shift count negative or too big, undefined behavior

This isn't a behavior problem - the << operator won't be used in this case, and that should be detected at compile time. But does anyone have any suggestions about how to rewrite the macro to avoid the warning? Or, failing that, how to redesign the macro interface for this?

Thanks in advance

© Stack Overflow or respective owner

Related posts about c

    Related posts about macros