Search code examples
pythonbinaryhexsigned

Signed decimal from a signed hex short in python


I was wondering if theres any easy and fast way to obtain the decimal value of a signed hex in python.

What I do to check the value of a hex code is just open up python in terminal and type in the hex, it returns the decimal like this:

>>>0x0024
36
>>>0xcafe
51966

So I was wondering, is there any way that I could do that for signed short hex? for example 0xfffc should return -4


Solution

  • If you can use NumPy numerical types you could use np.int16 type conversion

    >>> import numpy as np
    >>> np.int16(0x0024)
    36
    >>> np.int16(0xcafe)
    -13570
    >>> np.int16(0xfffc)
    -4
    >>> np.uint16(0xfffc)
    65532
    >>> np.uint16(0xcafe)
    51966
    

    Python Language specifies a unified representation for integer numbers, the numbers.Integral class, a subtype of numbers.Rational. In Python 3 there are no specific constraints on the range of this type. In Python 2 only the minimal range is specified, that is numbers.Integral should have at least the range of -2147483648 through 2147483647, that corresponds to the 32 bit representation.

    NumPy implementation is closer to the machine architecture. To implement numeric operations efficiently it provides fixed width datatypes, such as int8, int16, int32, and int64.