-1

I've been struggling for a while doing that and can not find the right way to do it. I have a HEX

8a:01

which is the unsigned INT16

394

How can I do that in python 3.X ?

Thanks in advance

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
deubNippon
  • 139
  • 1
  • 2
  • 7

1 Answers1

3

You can convert using the binascii and struct modules from the standard library:

>>> import binascii
>>> import struct
>>> import sys

# Check our system's byte order
>>> sys.byteorder
'little'
>>> hx = '8a01'
# convert hex to bytes
>>> bs = binascii.unhexlify(hx)
>>> bs
b'\x8a\x01'
# struct module expects ints to be four bytes long, so pad to make up the length
>>> padded = bs + b'\x00\x00'
# Ask struct to unpack a little-endian unsigned int.
>>> i = struct.unpack('<I', padded)
>>> i
(394,)

Update

This question has been closed as a duplicate. The duplicate solution doesn't produce the required result:

>>> int('8a01', 16)
35329

However it works as expected if the order of bytes is reversed:

>>> int('018a', 16)
394

This is because the int builtin function assumes that the hexstring is ordered in the same way we order base 10 numbers on paper, that is the leftmost values are the most significant. The initial value 0x8a01 has the least significant values on the left, hence using int to convert from base 16 produces the wrong result.

However in Python3 we can still use int to produce a simpler solution, using int.from_bytes.

>>> hx = '8a01'
>>> bs = binascii.unhexlify(hx)
>>> bs
b'\x8a\x01'
>>> int.from_bytes(bs, byteorder=sys.byteorder)
394
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153