Negative hex to int

Ben Finney bignose+hates-spam at benfinney.id.au
Wed Jun 14 20:31:12 EDT 2006


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::

    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.

            >>> 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
            >>> value_from_reading('100')
            -128
            >>> 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.

-- 
 \       "Remorse: Regret that one waited so long to do it."  -- Henry |
  `\                                                        L. Mencken |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list