checking for overflow in C
Paul Hudson
paul at moncam.co.uk
Wed May 10 21:22:44 AEST 1989
This does it, slowly, and is really over cautious. Typedefs and constants
self-explanatory, I hope.
Feel free to criticise, but constructively, please!
Paul Hudson MAIL: Monotype ADG, Science Park, Cambridge, CB4 4FQ, UK.
PHONE: +44 (223) 420018 EMAIL: paul at moncam.co.uk,
;" FAX: +44 (223) 420911 ...!ukc!acorn!moncam!paul
`"";";" "/dev/null full: please empty the bit bucket"
Integer a,b;
unsigned long hi_a, lo_a, hi_b, lo_b;
Integer result, temp = 0;
logical minus = FALSE;
logical overflowed = FALSE;
a = one->value.integer;
b = two->value.integer;
if (a < 0)
{
if (a != MIN_INTEGER) a = (-a);
minus = TRUE;
}
if (b < 0)
{
if (b != MIN_INTEGER) b = (-b);
minus = !minus;
}
hi_a = (unsigned long)a >> 16;
lo_a = (unsigned long)a & ( (1<<16) -1);
hi_b = (unsigned long)b >> 16;
lo_b = (unsigned long)b & ( (1<<16) -1);
if (hi_a == 0)
{
temp = hi_b * lo_a;
}
else if (hi_b == 0)
{
temp = hi_a * lo_b;
}
else overflowed = TRUE;
if (temp >= (1<<15)) overflowed = TRUE;
result = lo_a * lo_b;
if (result < 0) overflowed = TRUE;
result += (temp << 16);
if (result < 0) overflowed = TRUE;
result = minus ? -result : result;
--
Paul Hudson MAIL: Monotype ADG, Science Park, Cambridge, CB4 4FQ, UK.
PHONE: +44 (223) 420018 EMAIL: paul at moncam.co.uk,
;" FAX: +44 (223) 420911 ...!ukc!acorn!moncam!paul
`"";";" "/dev/null full: please empty the bit bucket"
More information about the Comp.lang.c
mailing list