title: C++ left shift overflow for negative numbers
body: <p>As shown below, the code has a bug. When input a = -1, b = 1, one of the line has runtime error. Could you please help me understand how (a &amp; b) becomes INT_MIN?</p>
  
  <p>In my understanding, -1 is represented as 32-bit binary format 0xFFFFFFFF, and 1 is represented as 32-bit format 0x00000001, thus (-1 &amp; 1) will become 0x00000001. And my python command also shows '0b1' as result. Why does it report the error of INT_MIN?</p>
  
  <pre><code>int getSum(int a, int b) {
      while (b != 0) {
          int carry = (a &amp; b) &lt;&lt; 1;//BUG! left shift of negative value -2147483648
          a = a ^ b;
          b = carry;
      }
  
      return a;
  }
  </code></pre>
  
  <p>Update: Is right shift for negative numbers well-defined? It seems ok to right shift negative numbers as long as it satisfies the requirements as quoted below.</p>
  
  <p>From cppreference.com, </p>
  
  <blockquote>
    <p>For unsigned a and for signed a with nonnegative values, the value of
    a >> b is the integer part of a/2b . For negative a, the value of a >>
    b is implementation-defined (in most implementations, this performs
    arithmetic right shift, so that the result remains negative).</p>
    
    <p>In any case, if the value of the right operand is negative or is
    greater or equal to the number of bits in the promoted left operand,
    the behavior is undefined.</p>
  </blockquote>