Index Home About Blog
From: henry@spsystems.net (Henry Spencer)
Newsgroups: comp.compilers
Subject: Re: 1 - 1, 1 -1, 1-1, 1 - -1 and -2147483648
Date: 31 Jan 2006 21:23:00 -0500
Message-ID: <06-01-147@comp.compilers>
Keywords: lex, arithmetic

Edsko de Vries <devriese@cs.tcd.ie> wrote:
>The problem is, of course, overflow: -2147483648 is a valid negative
>number (assuming 32-bit numbers), but the integer 2147483648 is _not_ a
>valid positive number...  Is there a good solution...?

The hack that has been used for this in the past is to compute and store a
number as the negative of its actual value (temporarily, until you know
whether there's a unary minus in front).

If that's too distasteful, you really have to find an extra bit somewhere:

+ Store the constant as an unsigned number (32-bit unsigned goes up to
  4_294_967_295 without overflow, so 2_147_483_648 is no problem),
  until you know the sign.

+ Use a larger signed type, if you have one.

+ Use a bignum (unlimited-length integer) library.

+ Store the number as a string, unconverted, until you know its sign.

--
spsystems.net is temporarily off the air;               |   Henry Spencer
mail to henry at zoo.utoronto.ca instead.               | henry@spsystems.net

Index Home About Blog