
Am 09.07.2013 01:27 schröbte Roberto Ierusalimschy:
There is also this stackoverflow solution[4], but AFAICT it is only guaranteed to work for C99 and up ...If the machine does not use two complement, doing arithmetic over unsigned versions of signed integers will not give the correct results anyway (this is the privilege of twocomplement arithmetic), so the conversion back to signed is the least of the problems.
I'm not sure I can follow, but arithmetic on unsigned integers always behaves like two's complement arithmetic, although it may be slower on machines without the necessary hardware. Same goes for conversions from signed to unsigned integers, so the only problem I can see (even on weird architectures) is the cast from unsigned to signed ...
3.1.2.5 Types[...] A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.
3.2.1.2 Signed and unsigned integers[...] When a signed integer is converted to an unsigned integer with equal or greater size, if the value of the signed integer is nonnegative, its value is unchanged. Otherwise: if the unsigned integer has greater size, the signed integer is first promoted to the signed integer corresponding to the unsigned integer; the value is converted to unsigned by adding to it one greater than the largest number that can be represented in the unsigned integer type. /22/
 Roberto
Philipp