title: How to detect/prevent a counter overflow
body: <p>I have a counter on a 16 bits field that is incremented/decremented over the time by a hardware peripheral.<br/>
  I sample its value periodically to sum the difference into a 32bits field.</p>
  
  <p>My problem is to detect the overflow/underflow of the 16 bits field when computing the difference.</p>
  
  <p>Let's take an example:<br/>
  At sample n-1, the counter value Vn-1 is 65530.<br/>
  As sample n, the counter value Vn is 4.<br/>
  The counter has been incremented by 10. But the difference (Vn - Vn-1), will be something like 65529 (not sure of the exact value).</p>
  
  <p>The only way I found to detect this overflow is to compare the difference value to a fixed value greater than the max increment (I choose 10000).<br/>
  Do you know a solution to manage this overflow without comparing to this subjective value?</p>
  
  <p>Here is a code example:</p>
  
  <pre><code>static sint32 overallCount = 0;
  sint32 diff;
  static sint16 previousValue = 0;
  sint16 currentValue;
  
  currentValue = sampleValue();
  
  diff = ((sint32) currentValue) - previousValue;
  if(diff &gt; 10000) {
      diff -= 65536;
  } else if ((-diff) &gt; 10000) {
      diff += 65536;
  }
  
  overallCount += diff;
  </code></pre>