Search code examples
cc99bit-fieldsc11

How to calculate the maximum supported value of a signed bit-field?


Suppose my project includes a header from a 3rd party library that contains this:

struct foo {
    signed int x:4;
};

Without assuming that the bit-field will always have width 4, and without relying on implementation-defined behavior, how can I determine the maximum value that can be stored in member x?


Solution

  • Basically you can't. The issue is the same as for determining INT_MAX or INT_MIN: because you can't determine these yourself, the compiler implementation has to provide these values. (All you could do to determine the position of the sign bit has implementation defined (or even undefined) behavior: overflow, shift operators)

    For bitfields the implementation can't provide these values, so you are stuck.

    This is one of the reasons bitfields really shouldn't be signed. Bitfields are for bit manipulations and nothing else, the sign bit is then just wasted.

    If your field would be unsigned things would be easy. You'd just have to store -1 in it and you'd get the value with all ones, the maximum value for the "type".