| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Dokkio Sidebar applies AI to make browsing the web faster and more productive. Whenever you open Sidebar, you'll get an AI summary of the web page and can ask any question you like about the content of the page! Try Dokkio Sidebar for free.

View
 

Saturated Addition

This version was saved 14 years, 8 months ago View current version     Page history
Saved by Kenneth Finnegan
on September 23, 2008 at 3:07:21 pm
 

These functions can be used when you're adding numbers together and don't want the total to overflow.  Normally, when an addition overflows, it just drops back down to 0 and you're left with however much is left over after the overflow. 

 

If you were doing something like calculating the distance between two points, and it overflowed, they would appear to be very close to each other.  Using these functions, you still won't know how far apart they are, but you'll be able to see that the points are very far apart (at least 0xFFFFFFFF, in the case of 32 bits).

 

Code:

#include <stdint.t>

uint16_t saturateadd16(uint16_t a, uint16_t b) {
    return (a > 0xFFFF - b) ? 0xFFFF : a + b;
}

uint32_t saturateadd32(uint32_t a, uint32_t b) {
    return (a > 0xFFFFFFFF - b) ? 0xFFFFFFFF : a + b;
}

  

Usage:

 

uint32_t x=14, y=15, sum;

sum = saturateadd32(x, y);

Extensions:

The functions can easily be adapted to 8 or 64 bit operations at well.

 

There is significant overhead in function calls, so consider inlining the functions or changing them to macros instead.


Sources:

http://stackoverflow.com/questions/121240/saturating-addition-in-c

Comments (0)

You don't have permission to comment on this page.