Re: Dealing with possible overflows

From: Allan Bruce (allanmb_at_TAKEAWAYf2s.com)
Date: 08/02/04


Date: Mon, 2 Aug 2004 09:34:58 +0100


"MWB" <mandir_wahin_banayenge@yahoo.com> wrote in message
news:f498b759.0408012338.759e879c@posting.google.com...
> Hi CLC,
> Suppose I want to evaluate (x*y)/z where x,y,z are unsigned int's.
> In some cases, though (x*y) might overflow the (xy)/z (the actual
> product) might be representable as an unsigned int, I was wondering
> how to get the correct answer in such a case.
> In one specific case the answer is easy to see : x is the only "large"
> number among the three- y and z are small.
> Then calculate the answer as (x/z)*y + ((x -(x/z)*z)*y)/z

I would cast to a double for the calculation, and then back to unsigned int.
This is likely to be faster, and easier to understand.
Allan



Relevant Pages

  • Re: IP address and matching it to a network/netmask
    ... If your unsigned int is only 16 bits, then that calculation of ... if you are attempting to determine whether one range fully encloses ... the other or if there is some overlap or no overlap. ...
    (comp.lang.c)
  • Re: Question about cast
    ... the cast specifies a conversion even if the type ... machine unsigned int is 32 bits and unsigned char is 8 ... A cast is simply an operator that specifies a conversion. ... document belongs in comp.std.c; discussion of the language it defines ...
    (comp.lang.c)
  • Re: size of a struct
    ... "an unsigned integer" might not be an unsigned int. ... So in C99 we would have to cast it to unsigned long long? ... If your runtime library is C99 compliant (which it might not be even ...
    (comp.lang.c)
  • Re: cast vs. suffixes
    ... Either you use an explicit cast, as in: (unsigned int) 1234 or you use the UL suffixes, as in: ... Since the preprocessor operates at an early stage of compilation before types "exist," it cannot evaluate cast operators -- since casts are all about type conversions and there aren't any types yet, there's really nothing the preprocessor can do with them. ...
    (comp.lang.c)
  • Re: Bit mask
    ... >>there would be will probably get lost in compiler optimisation. ... > common idiom and that you needed to cast ~0x07 to unsigned char. ... Why would the cast be needed? ... will be promoted back to int (probably - unsigned int is theoretically ...
    (comp.lang.c)