title: Saturating signed integer addition with only bitwise operators in C (HW)
body: <p>For a homework assignment, I have to write a function in C that adds together two signed integers, but returns INT_MAX if there would be positive overflow and INT_MIN if there would be negative overflow. I have to follow very strict restrictions in what operators I can use. All integers are in two's complement form, right shifts are arithmetic, and the integer size is variable (I can find it with sizeof(int)&lt;&lt;3). I can't use contitionals, loops, comparison operators, or casting. I can only use bitwise and logical operators, addition and subtraction, equality tests, and the integer constants INT_MAX and INT_MIN.</p>
  
  <p>I know that overflow can be detected if the two inputs have the same sign and the result has a different sign. I've gotten to the point where I have a flag showing if the equation did overflow. I have no idea how to get from there to the end product. This is what I have so far: </p>
  
  <pre><code>int saturating_add(int x, int y){
      int w = sizeof(int)&lt;&lt;3;
      int result = x+y;
      int signX = (x&gt;&gt;w-1)&amp;0x01;//Sign bit of X
      int signY = (y&gt;&gt;w-1)&amp;0x01;//Sign bit of Y
      int resultSign = (result&gt;&gt;w-1)&amp;0x01; //Sign bit of result
      int canOverflow = ~(signX ^ signY); //If they're the same sign, they can overflow
      int didOverflow = (resultSign^signX)&amp;canOverflow; //1 if input signs are same and result sign different, 0 otherwise
  
  }
  </code></pre>
  
  <p>I'm trying to follow the answer shown at <a href="https://stackoverflow.com/questions/5277623/bitwise-saturated-addition-in-c-hw">Bitwise saturated addition in C (HW)</a>, but I'm stuck on the part where I have to fill an integer with the same bit for all but the sign bit (1 goes to 0111..11 and 0 goes to 0000.00). I have no idea what the "combination of shifts and ORs" would be.</p>