16 bit hex into 14 bit signed int python?
<p>I get a 16 bit Hex number (so 4 digits) from a sensor and want to convert it into a signed integer so I can actually use it.
There are plenty of codes on the internet that get the job done, but with this sensor it is a bit more arkward.</p>

<p>In fact, the number has only 14 bit, the first two (from the left) are irrelevant.
I tried to do it (in Python 3) but failed pretty hard.
Any suggestions how to "cut" the first two digits of the number and then make the rest a signed integer? 
The Datasheet says, that E002 should be -8190 ane 1FFE should be +8190.</p>

<p>Thanks a lot!</p>

<p>There is a general algorithm for sign-extending a two's-complement integer value <code>val</code> whose number of bits is <code>nbits</code> (so that the top-most of those bits is the sign bit).</p>

<p>That algorithm is:</p>

<ol>
<li>treat the value as a non-negative number, and if needed, mask off additional bits</li>
<li>invert the sign bit, still treating the result as a non-negative number</li>
<li>subtract the numeric value of the sign bit considered as a non-negative number, producing as a result, a <em>signed</em> number.</li>
</ol>

<p>Expressing this algorithm in Python produces:</p>

<pre><code>from __future__ import print_function

def sext(val, nbits):
    assert nbits &gt; 0
    signbit = 1 &lt;&lt; (nbits - 1)
    mask = (1 &lt;&lt; nbits) - 1
    return ((val &amp; mask) ^ signbit) - signbit

if __name__ == '__main__':
    print('sext(0xe002, 14) =', sext(0xe002, 14))
    print('sext(0x1ffe, 14) =', sext(0x1ffe, 14))
</code></pre>

<p>which when run shows the desired results:</p>

<pre><code>sext(0xe002, 14) = -8190
sext(0x1ffe, 14) = 8190
</code></pre>

python cut bits data-conversion