LeedMx
LeedMx

Reputation: 434

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

Upvotes: 1

Views: 3572

Answers (3)

atline
atline

Reputation: 31564

import ctypes

def hex2dec(v):
    return ctypes.c_int16(v).value

print hex2dec(0xfffc)
print hex2dec(0x0024)
print hex2dec(0xcafe)

Upvotes: 5

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95873

You can use the int classmethod from_bytes and provide it with the bytes:

>>> int.from_bytes(b'\xfc\xff', signed=True, byteorder='little')
-4

Upvotes: 3

Dima Chubarov
Dima Chubarov

Reputation: 17159

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.

Upvotes: 1

Related Questions