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
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
import ctypes
def hex2dec(v):
return ctypes.c_int16(v).value
print hex2dec(0xfffc)
print hex2dec(0x0024)
print hex2dec(0xcafe)
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
.
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.