title: C - Saturating Signed Integer Multiplication with Bitwise Operators
body: <p>Alright, so the assignment I have to do is to multiply a signed integer by 2 and return the value. If the value overflows then saturate it by returning Tmin or Tmax instead. The challenge is using only these logical operators (! ~ &amp; ^ | + &lt;&lt; >>) with no (if statements, loops, etc.) and only allowed a maximum of 20 logical operators.</p>
  
  <p>Now my thought process to tackle this problem was first to find the limits. So I divided Tmin/max by 2 to get the boundaries. Here's what I have:</p>
  
  <p><strong>Positive</strong></p>
  
  <p>This and higher works:</p>
  
  <pre><code>1100000...
  </code></pre>
  
  <p>This and lower doesn't:</p>
  
  <pre><code>1011111...
  </code></pre>
  
  <p>If it doesn't work I need to return this:</p>
  
  <pre><code>100000...
  </code></pre>
  
  <p><strong>Negative</strong></p>
  
  <p>This and lower works:</p>
  
  <pre><code>0011111...
  </code></pre>
  
  <p>This and higher doesn't:</p>
  
  <pre><code>0100000...
  </code></pre>
  
  <p>If it doesn't work I need to return this:</p>
  
  <pre><code>011111...
  </code></pre>
  
  <p>Otherwise I have to return:</p>
  
  <pre><code>2 * x;
  </code></pre>
  
  <p>(the integers are 32-bit by the way)</p>
  
  <p>I see that the first two bits are important in determining whether or not the problem should return 2*x or the limits. For example an XOR would do since if the first to bits are the same then 2*x should be returned otherwise the limits should be returned. Another if statement is then needed for the sign of the integer for it is negative Tmin needs to be returned, otherwise Tmax needs to be.</p>
  
  <p>Now my question is, how do you do this without using if statements? xD Or a better question is the way I am planning this out going to work or even feasible under the constraints? Or even better question is whether there is an easier way to solve this, and if so how? Any help would be greatly appreciated!</p>