In n-bit two's complement, bits have value:
bit 0 = 20
bit 1 = 21
bit n-2 = 2n-2
bit n-1 = -2n-1
But bit n-1 has value 2n-1 when unsigned, so the number is 2n too high. Subtract 2n if bit n-1 is set:
>>> def twos_complement(hexstr,bits):
... value = int(hexstr,16)
... if value & (1 << (bits-1)):
... value -= 1 << bits
... return value
...
>>> twos_complement('FFFE',16)
-2
>>> twos_complement('7FFF',16)
32767
>>> twos_complement('7F',8)
127
>>> twos_complement('FF',8)
-1
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…