What is the most reliable way to detect whether the architecture uses one's or two's complement representation in C++?
Asked
Active
Viewed 2,425 times
16
-
4If those are the only options, check `(-1) & 1`. – Daniel Fischer May 11 '13 at 19:46
-
1@BasileStarynkevitch I work with heterogeneous supercomputer architectures and I want to record that at the beginning of each binary file to know whether it is compatible with the architecture that will try to read it. – Vincent May 11 '13 at 19:48
-
doesn't little or big endianness matter much more today? And basically you are doing serialization, and there are libraries to do that reliably today..... [s11n](http://s11n.net/) and others – Basile Starynkevitch May 11 '13 at 19:52
-
2@Vincent - just compare "-1" with "~0". They're *equal* with twos complement, they are *not equal* with ones complement. – paulsm4 May 11 '13 at 19:53
1 Answers
13
You shouldn't have to worry - there aren't too many ones complement machines out there :)
But the easiest thing might be to compare "-1" with ~0.

paulsm4
- 114,292
- 17
- 138
- 190
-
-
9@R.MartinhoFernandes: Of course it is. They'll be equal on a twos-complement implementation, and not on ones-complement (or sign-magnitude) implementations, and so can be used to test which representation is used. – Mike Seymour May 12 '13 at 00:40
-
-
4
-
there are many ways to simulate `static_assert` if it's not available https://stackoverflow.com/q/807244/995714 https://stackoverflow.com/q/6765770/995714 – phuclv Dec 25 '17 at 03:10
-
Or you can just compare -1 with ~0. If they're not equal, you've got ones complement hardware. – paulsm4 Dec 25 '17 at 04:36
-
2
-
5@plasmacel on a sign-magnitude system ~0 is -INT_MAX which is also not -1 – phuclv Mar 06 '19 at 16:56
-
@MartinYork Assuming paulsm4's technique is sufficient, `#if ~0==-1` [also works](https://godbolt.org/z/hTTYKP1r4). Of course in C++11+ a `static_assert` or `constexpr` variable is preferable. – Spencer Jan 26 '23 at 15:03