Python converts FFFF to 'nominal value', decimal 65535
input = 'FFFF' val = int(input,16) # is 65535
You want this to be interpreted as a 16-bit signed number. In the code below, the lower 16 bits of any number will be accepted, and "sign-extend", i.e. Interpret as a 16-bit signed value and deliver the corresponding integer
val16 = ((val+0x8000)&0xFFFF) - 0x8000
It is easy to generalize.
def sxtn( x, bits ): h= 1<<(bits-1) m = (1<<bits)-1 return ((x+h) & m)-h
greggo
source share