How to convert ASCII hexadecimal string to signed integer

Input = 'FFFF' # 4 ASCII F

desired result ... -1 as an integer

code verified:

hexstring = 'FFFF' result = (int(hexstring,16)) print result #65535 

Result: 65535

Nothing I tried seemed to admit that "FFFF" is a negative number.

+7
source share
2 answers

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 
+10
source

In a language like C, "FFFF" can be interpreted as a signed (-1) or unsigned (65535) value. You can use the Python structure module to force the interpretation you want.

Please note that there may be problems with the content that no attempts are made in the code below, and it does not process data longer than 16 bits, so you will need to adapt if any of these cases is in effect for you.

 import struct input = 'FFFF' # first, convert to an integer. Python going to treat it as an unsigned value. unsignedVal = int(input, 16) assert(65535 == unsignedVal) # pack that value into a format that the struct module can work with, as an # unsigned short integer packed = struct.pack('H', unsignedVal) assert('\xff\xff' == packed) # ..then UNpack it as a signed short integer signedVal = struct.unpack('h', packed)[0] assert(-1 == signedVal) 
+2
source

All Articles