title: How to accurately emulate `int32`, signed 2's complement 32-bit integers, in python
body: <p>Python supports arbitrary bit-length integers, but I would like to emulate <code>int32</code>, 32-bit integers, in all their overflow glory.</p>
  <p>I have few questions and comments about this</p>
  <ol>
  <li><code>int32</code> has <code>INT32_MIN = -(1 &lt;&lt; 31)</code> and <code>INT32_MAX = (1 &lt;&lt; 31) - 1</code></li>
  <li>Does python use 2's complement?</li>
  <li>in <code>int32</code>, a positive <code>int32</code> has leading zeros up to the 31st bit and a negative <code>int32</code> has leading ones up to the 31st bit (this is because they are 2's complement).</li>
  <li>in python, a positive integer is considered to have infinitely (or arbitrarily) many leading ones and a negative integer is considered to have infinitely (or arbitrarily) many leadings ones.</li>
  </ol>
  <p>So for example:</p>
  <p><code>123</code> would look like:</p>
  <ul>
  <li><code>0b0000_0000_0000_0000_0000_0000_0111_1011</code> in <code>int32</code></li>
  <li><code>0b...0_0111_1011</code> in python (<code>...0</code> indicates infinitely many leading <code>0</code>'s)</li>
  </ul>
  <p><code>-123</code> would look like:</p>
  <ul>
  <li><code>0b1111_1111_1111_1111_1111_1111_1000_0101</code> in <code>int32</code></li>
  <li><code>0b...1_1000_0101</code> in python (<code>...1</code> indicates infinitely many leading <code>1</code>'s)</li>
  </ul>
  <p>Given all this, I've come up with this code to emulate <code>int32</code>, but would like a check:</p>
  <pre><code>INT32_MIN = -(1 &lt;&lt; 31)
  INT32_MAX = (1 &lt;&lt; 31) - 1
  INT32_MASK = (1 &lt;&lt; 32) - 1
  INT32_SIGNBIT = 1 &lt;&lt; 31
  
  def int32(x):
      sb = bool(x &amp; INT32_SIGNBIT)
      i32 = x &amp; INT32_MASK
      if sb:
          i32 += ~INT32_MASK
      return i32
  
  a = int32(INT32_MAX + 1)
  b = int32(INT32_MIN - 1)
  aa = a == INT32_MIN
  bb = b == INT32_MAX
  </code></pre>
  <p>It does seem to overflow as desired when you add <code>1</code> to <code>INT32_MAX</code> or subtract <code>1</code> from <code>INT32_MIN</code>, so that gives me some confidence that it is correct, but that's just two test cases. Does this look correct to you?</p>