Negative hex to int
John Machin
sjmachin at lexicon.net
Wed Jun 14 21:09:27 EDT 2006
On 15/06/2006 10:31 AM, Ben Finney wrote:
> andreas.lydersen at gmail.com writes:
>
>> The problem is negative values. If the unit returns the hex value
>> 'e7', it means -25, but python says it's 231:
>
> Python is right. There is no "negative bit" in Python numbers, now
> that unification of 'long' and 'int' is complete; numbers can grow
> indefinitely large.
>
> If you want a special interpretation of the value, you'll have to
> calculate it.
>
> Example assuming you want a one's-complement interpretation::
Given that the OP had to ask the question at all, it is doubtful that he
knows what "one's-complement" means. He may well not be alone -- see later.
>
> def value_from_reading(num):
> """ Gets the integer value from the reading string.
> num is a positive hexadecimal number as a string.
> Numbers greater than 0x7F are interpreted as negative,
> with magnitude greater than 0x7F being the negative value.
> Only the lowest 15 bits are used for the magnitude.
thing & 0x7F looks like lowest 7 bits to me.
>
> >>> value_from_reading('00')
> 0
> >>> value_from_reading('05')
> 5
> >>> value_from_reading('7f')
> 127
> >>> value_from_reading('80')
> -128
> >>> value_from_reading('e7')
> -25
> >>> value_from_reading('ff')
> -1
Looks like TWOS complement to me.
> >>> value_from_reading('100')
> -128
Same result as '80'?
In any case the OP gave no indication that he was getting more than two
hex digits. His desired interpretation of 'e7' as -25 strongly indicates
that he's getting only 2 hex digits.
> >>> value_from_reading('fff')
> -1
>
> """
> num_base = 16
> negative_threshold = 0x7F
> int_val = int(num, num_base)
> if int_val > negative_threshold:
> magnitude = (int_val & negative_threshold)
> int_val = -(1 + negative_threshold - magnitude)
> return int_val
>
> Adjust for whatever algorithm you want to use. Consult a book of
> algorithms if you want a better implementation than my off-the-cuff
> brute-force approach.
More information about the Python-list
mailing list