How to detect encodings on signed integers in C? How to detect encodings on signed integers in C? c c

How to detect encodings on signed integers in C?


You just have to check the low order bits of the constant -1 with something like -1 & 3. This evaluates to

  1. for sign and magnitude,
  2. for one's complement and
  3. for two's complement.

This should even be possible to do in a preprocessor expression inside #if #else constructs.


Detecting one's complement should be pretty simple -- something like if (-x == ~x). Detecting two's complement should be just about as easy: if (-x == ~x + 1). If it's neither of those, then it must be sign/magnitude.


Why not do it at compile time? You could have the build scripts/makefile compile a test program if need be, but then use the preprocessor to do conditional compilation. This also means performance is much less important, because it only runs once per compile, rather than once per run.