Representation of signed integers

suggest change

Through C17, each signed integer type may use sign-magnitude, ones’ complement, or two’s complement; which one is implementation-defined. C23 requires two’s complement for every signed integer type. For a signed integer type at least as wide as int, the two lowest-order bits of the value -1 identify the representation, like so:

enum { sign_magnitude = 1, ones_compl = 2, twos_compl = 3, };
#define SIGN_REP(T) ((T)-1 & (T)3)

switch (SIGN_REP(long)) {
   case sign_magnitude: { /* do something */ break; }
   case ones_compl:     { /* do otherwise */ break; }
   case twos_compl:     { /* do yet else  */ break; }
   case 0:  { static_assert(SIGN_REP(long), "bogus sign representation"); }
}

The same pattern applies to the representation of narrower types, but they cannot be tested by this technique because the operands of & are subject to “the usual arithmetic conversions” before the result is computed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents