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

Reading and printing numbers

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:
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
	NUM, DIGIT := DIVIDE(NUM, 10)	[usual, i.e. FORTRAN-style, divide]
	print("0" - [NOT +!] DIGIT)
until NUM = 0