• To: (BUG LISPM) at MIT-AI, s1arch at SU-AI, nil at MIT-MC
• Subject: Reading and printing numbers
• From: GLS at MIT-AI (Guy L. Steele, Jr.)
• Date: Sun ,4 Feb 79 20:44:00 EDT

```In this month's SIGPLAN Notices is one of those "popular computing how-to"
items like my flaming "Arithmetic Shift" paper which points out one
of those trivial "how to do it right" things that yoou kick yourself
for not thinking of it.
The trick described is when reading a signed integer, how do you deal
with the most negative integer?  For sixteen-bit words, for example,
if you read "-32768" in the usual way of noting the "-", then reading
"32768" and negating it, you find that reading "32768" overflows and
you lose big in some situations.
James Low suggests simply reading the number in negative form, then
negating if the "-" was NOT seen.  Thus:
RESULT := 0
while "moredigits" do
RESULT := RESULT *10 - [NOT +!] "nextdigit"
if "sign" is positive then RESULT := - RESULT
This correctly accumulates all valid numbers without overflow.

The article did not say so, but I note that the same holds true
for printing:
if NUM < 0 then print("-") else NUM := - NUM
repeat
NUM, DIGIT := DIVIDE(NUM, 10)	[usual, i.e. FORTRAN-style, divide]
print("0" - [NOT +!] DIGIT)
until NUM = 0
```