简体   繁体   中英

Conversion from hex to signed int not working

I'm trying to convert this hex string F1 into a signed integer.
So I should get as result -15

I have this Python function right here which works good, but somehow doesn't work for this string F1

Code:

def get_signed_value(value):
    return -(value & 0x8000) | (value & 0x7fff)  

If I pass for example FF5F as value, then I get -161 as response which is correct.
But if I pass F1 I get 241 as response which is not the correct value.

your function is designed for a 16-bit number with a value range of −32.768 (0x8000) to 32.767 (0x7fff) , while 0xf1 is only a 8-bit number with a value range of -128 (0x80) to 127 (0x7f) . Thus, the return statement in the function doesn't apply correctly.

You have to change the function according to what is the number of bits in your hex number. For 8-bit:

def get_8bit_signed_value(value):
    return -(value & 0x80) | (value & 0x7f)

Then

get_8bit_signed_value(int('0xf1', 16))

returns your desired -15 for 0xf1 . You can automate this function for bitnumbers with nbits digits by calculating the value range limits by 1 << (nbits-1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM