title: How to subtract two unsigned ints with wrap around or overflow
body: <p>There are two unsigned ints (x and y) that need to be subtracted. x is always larger than y.  However, both x and y can wrap around; for example, if they were both bytes, after 0xff comes 0x00.  The problem case is if x wraps around, while y does not. Now x appears to be smaller than y. Luckily, x will not wrap around twice (only once is guaranteed). Assuming bytes, x has wrapped and is now 0x2, whereas y has not and is 0xFE. The right answer of x - y is supposed to be 0x4. </p>
  
  <p>Maybe, </p>
  
  <pre><code>( x &gt; y) ? (x-y) : (x+0xff-y);
  </code></pre>
  
  <p>But I think there is another way, something involving 2s compliment?, and in this embedded system, x and y are the largest unsigned int types, so adding 0xff... is not possible</p>
  
  <p>What is the best way to write the statement (target language is C)?</p>