Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a hex ASCII string to a signed integer

Tags:

python

binary

Input = 'FFFF' # 4 ASCII F's

desired result ... -1 as an integer

code tried:

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

Result: 65535

Nothing that I have tried seems to recognized that a 'FFFF' is a representation of a negative number.

like image 762
user1923597 Avatar asked Dec 22 '12 13:12

user1923597


1 Answers

Python converts FFFF at 'face value', to decimal 65535

input = 'FFFF'
val = int(input,16) # is 65535

You want it interpreted as a 16-bit signed number. The code below will take the lower 16 bits of any number, and 'sign-extend', i.e. interpret as a 16-bit signed value and deliver the corresponding integer

val16 = ((val+0x8000)&0xFFFF) - 0x8000

This is easily generalized

def sxtn( x, bits ):
     h= 1<<(bits-1)
     m = (1<<bits)-1
     return ((x+h) & m)-h
like image 81
greggo Avatar answered Nov 15 '22 14:11

greggo