lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Am 09.07.2013 15:00 schröbte Roberto Ierusalimschy:
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 two-complement 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, [...]

Exactly. So, if the machine does not use two complement arithmetic,
this behavior will not be the correct one for (the machine's) signed
arithmetic.

I think we agree on the end result, but ...


Simple example: Assume a machine using sign-and-magnitude (I will use
only four bits to simplify); then we do 3+(-2)=1. In sign-and-magnitue,
this becomes 0011+1010=0001. However, if we do the computation with
unsigneds, we have 0011+1010=1101, the wrong answer.

    SM: sign-and-magnitude, 2C: two's complement, UINT_MAX = 2^4-1 = 15

Both operands of the calculation
    0011 (SM) + 1010 (SM)
get converted to unsigned according to the rules I quoted in my last mail (the first keeps its value, because it is nonnegative, the second is adjusted by UINT_MAX+1, which makes it -2+15+1 = 14 = 1110 (2C)):
    0011 (2C) + 1110 (2C)
The result is
    1 0001 (2C) % (UINT_MAX+1) = 0001 (2C)
which can be transformed to SM without problems, because it has a valid representation as a signed integer.
    0001 (SM)

So there is no problem for this example, the trouble starts when the result of the unsigned arithmetic gets greater than 0111 (2C), in which case the implementation is free to raise signals or whatever.