This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

Integer overflow

Hello to everyone.

When I have to calculate the average of two integer numbers, first i have to add them. Sometimes an overflow occurs. One technique maybe to compare the result to one of the numbers, if result is lower, an overflow is recognized.

Is this good style or better use Assembler?

Parents
  • How about something like that:

    signed int Number1;
    signed int Number2;
    
    // Possibly CPU intensive, but quite accurate
    // even with odd numbers
    signed int AverageMethod1 = (signed int) ((long signed int)Number1 + (long signed int)Number2) / 2);
    // Faster but could be a couple of bits off
    // with odd numbers
    signed int AverageMethod2 = Number1 / 2 +  Number2 / 2;
    

    $0.02

Reply
  • How about something like that:

    signed int Number1;
    signed int Number2;
    
    // Possibly CPU intensive, but quite accurate
    // even with odd numbers
    signed int AverageMethod1 = (signed int) ((long signed int)Number1 + (long signed int)Number2) / 2);
    // Faster but could be a couple of bits off
    // with odd numbers
    signed int AverageMethod2 = Number1 / 2 +  Number2 / 2;
    

    $0.02

Children
No data