title: Converting bytes to signed numbers in Python
body: <p>I am faced with a problem in Python and I think I don't understand how signed numbers are handled in Python.  My logic works in Java where everything is signed so need some help in Python.</p>
  
  <p>I have some bytes that are coded in HEX and I need to decode them and interpret them to numbers.  The protocol are defined.</p>
  
  <p>Say the input may look like:<br>
      raw = '016402570389FFCF008F1205DB2206CA'
  And I decode like this:</p>
  
  <pre><code>bin_bytes = binascii.a2b_hex(raw)
  lsb = bin_bytes[5] &amp; 0xff
  msb = bin_bytes[6] &lt;&lt; 8
  aNumber = int(lsb | msb)
  print("     X: " + str(aNumber / 4000.0))
  </code></pre>
  
  <p>After dividing by 4000.0, X can be in a range of -0.000025 to +0.25.</p>
  
  <p>This logic works when X is in positive range.  When X is expected
  to be negative, I am getting back a positive number.
  I think I am not handling "msb" correctly when it is a signed number.
  How should I handlehandle negative signed number in
  Python?</p>
  
  <p>Any tips much appreciated.</p>