Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!cs.utexas.edu!uunet!mcvax!ukc!acorn!moncam!paul From: paul@moncam.co.uk (Paul Hudson) Newsgroups: comp.lang.c Subject: Re: checking for overflow in C Summary: Here's some code. Message-ID: <187@marvin.moncam.co.uk> Date: 10 May 89 11:22:44 GMT References: <13367@dartvax.Dartmouth.EDU> <10218@smoke.BRL.MIL> <436@cbnewsm.ATT.COM> Organization: Monotype ADG, Cambridge, UK Lines: 54 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@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@moncam.co.uk, ;" FAX: +44 (223) 420911 ...!ukc!acorn!moncam!paul `"";";" "/dev/null full: please empty the bit bucket"