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

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!


Saturated Addition

Page history last edited by Kenneth Finnegan 15 years, 8 months ago

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).



#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;



uint32_t x=14, y=15, sum;
sum = saturateadd32(x, y);


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.


A similar approach can be used for subtraction, multiplication, and division as well.  Multiplication and division will be more difficult than subtraction due to more edge cases.


This one is a little out of my league, but on an x86, if performance is key, you can use inline assembly...

uint32_t add(uint32_t a, uint32_t b) {
  #ifdef IA32
  __asm  {
    mov eax,a
    xor edx,edx
    add eax,b
    setnc dl
    dec edx
    or eax,edx
  // Portable version
  return sum;



Comments (0)

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