Sign in Join

Live chat for Free Pascal, Lazarus, Delphi and every Pascal programmer.

Mailing lists / fpc-devel / 2024-04

wrong result for abs(low(int64))

5 messages · 4 people ·

Reply by email Subscribe to this list Your subscription

Read-only archive. Use j and k to move between messages.

Martin Frb

The below writes:  -9223372036854775808

Shouldn't absolute return a positive number?

program Project1;
begin
   writeln( abs(low(int64)) );
end.
Seems
writeln( abs(low(longint)) );

also returns negative...

Reply by email

J. Gareth Moreton
to Martin Frb: The below writes:  -9223372036854775808 Shouldn't absolute return a positive number?…

Essentially, an arithmetic overflow is happening.  Since the largest Int64 possible is 9,223,372,036,853,775,807, going one above that (the result to abs(low(int64))) wraps back around to -9,223,372,036,853,775,808.

Internally, you can think about negating (positing?) a negative number as inverting the bits and then adding one (aka. two's complement), so low(int64) is 1000...000, which inverted becomes 0111...111, and then adding one results in 1000...000 again.

Kit

Martin Frb wrote 20 lines
The below writes:  -9223372036854775808 Shouldn't absolute return a positive number? program Project1; begin   writeln( abs(low(int64)) ); end. Seems writeln( abs(low(longint)) ); also returns negative... _______________________________________________ fpc-devel maillist  -  https://lists.freepascal.org/cgi-bin/mailman/listinfo/fpc-devel

Reply by email

Martin Frb
to J. Gareth Moreton
J. Gareth Moreton wrote 9 lines
Essentially, an arithmetic overflow is happening.  Since the largest Int64 possible is 9,223,372,036,853,775,807, going one above that (the result to abs(low(int64))) wraps back around to -9,223,372,036,853,775,808. Internally, you can think about negating (positing?) a negative number as inverting the bits and then adding one (aka. two's complement), so low(int64) is 1000...000, which inverted becomes 0111...111, and then adding one results in 1000...000 again.

I got that bit...

Initially I was surprised to find "abs" to return a signed number. After all, it will never be negative.

But, in the meantime I recalled that unsigned numbers will cause other issues when used in expressions.
"abs(-1)-2" would behave different.

Reply by email