The computer returns:
64447 32447
And if we add these together by doing:
PRINT %1088 + 64447, %33088 + 32447
we will get in both cases 65535!
Integer arithmetic is extremely fast, so we should have at least a way of representing signed integers in NextBASIC for both fast calculations as well as special cases, so NextBASIC does provide the way to deal with these numbers with the special SGN {...} keyword. What this does is, to treat any integer expression enclosed within it as a signed integer value (ranging from -32768 to 32767). All expressions enclosed within an SGN {...} block are called signed integer expressions. Signed integer expressions use all the same operators and functions as standard unsigned ones, but the arithmetic operators (+, -, *, /, MOD) and the relational operators (<, <=, >, >=, =, <>) treat their operands as signed values in the range -32768 to 32767. The other operators and functions can be used within a signed integer expression, but still treat their operands as unsigned.
Based on how two's complement works, theoretically you can work with just the two's complement numbers (which if regarded as unsigned integers, are also positive integers) but in these cases that would be very cumbersome to have to remember the equivalents instead of the actual number we want to involve in our calculation.
If say we need to do 1 + (-32300) - (-1) what would be easier to implement?
PRINT % SGN {1}+ SGN {-32300}- SGN {-1}
or
PRINT %1+33236-65535
There are obvious benefits on usability; and also non obvious benefits such as in the following example:
10 %x=0
20 PRINT %(x-1)>0,
%SGN{(x-1)>0}
which will result in:
1 0
on screen as in unsigned expressions 0-1 equals 65535 (see also the previous example) which is obviously larger than 0 while in signed expressions 0-1 equals -1 which is not larger than 0!
SGN {...}, also affects multiplication, division and MODulo operations. Consider this example (which also contains a pitfall!):
10 PRINT %10*-1
20 PRINT %10* SGN {-1}
30 PRINT % SGN {10* SGN {-1}}
40 PRINT % SGN {10*-1}
If you RUN this, you will see the following on screen:
65526
65526
ZX Spectrum Next User Manual, 3rd Edition (ISBN 978-1-5272-5496-1), written and illustrated by Phoebus R. Dokos. Copyright © 2020-2024 Phoebus Dokos / SpecNext Ltd. Licensed under CC BY-NC-SA 4.0. This is a transcription and can contain errors; check any doubt against the printed page.