title: Javascript twos complement
body: <p>The following python code seems to work very well to het the twos complement of a number:</p>
  
  <pre><code>def twos_comp(self, val, bits):
      if (val &amp; (1 &lt;&lt; (bits - 1))) != 0:
          val -= 1 &lt;&lt; bits
      return val
  </code></pre>
  
  <p>It is used as <code>num = self.twos_comp(int(binStr, 2), len(binStr))</code>
  where binStr is a string that contains an arbitrary length binary number.</p>
  
  <p>I need to do the exact same thing in javascript (for node.js).  I've been fighting it all day and am about to resign from the human race.  Clearly binary / bitwise math is not my strong suit.</p>
  
  <p>Could someone please assist so I can go on to more productive time wasting :-)</p>