On 2019-10-01 06:53, Hans Åberg wrote:
One should note that the unsigned types are required to be 2’s complement C/C++, unlike the signed ones, cf.
That is untrue by definition, since two's complement is strictly a mechanism for representing negative values, which the unsigned types do not do. They follow a "pure binary enumeration" (I think that's the wording). The unsigned types can *simulate* some aspects of two's complement quite well. Unsigned and two's complement addition basically look the same at the bit level; just the interpretation of the upper two bits is different for determining sign and overflow. If you're writing a software emulator for a two's complement CPU, you can use unsigned for the basic ALU operations. Code which uses unsigned numbers in a thoroughly disciplined way to simulate two's complement math does not represent the typical uses of the unsigned types in C programs. When unsigned types are used to simulate signed, comparisons must be done very carefully. The value UINT_MAX is representing -1 and so it has to compare less than zero. You need two write yourself a a twocomp_less(x, y) function and consistently use it to get this right. Most code that you will see in the wild that works with unsigned numbers still uses the regular < and > operators, though. (That's one way the bugs creep in.) Unsigned multiplication and division also require careful handling in order to correctly simulate two's complement.