What i am trying to do

I want to convert a 2-byte hexadecimal number assigned to a variable into a decimal number in Python2.7.

data_hex = rec [-2:]
print ("RX: {0}". format (codecs.encode (data_hex, 'hex_codec')))

Now, the execution result of this program is
RX: 029b.

I tried to convert to decimal with the following code

data_dec = int (data_hex, 16)
print (data_dec)

I got an error.

data_dec = int (data_hex, 16)
ValueError: invalid literal for int () with base 16: '\ x02 \ x9b'

If i write in the value, it can be converted without any problems, but
Is there another way to convert a variable (with the value I want to convert) in place of an int?

data_dec = int ('029b', 16)
print (data_dec)
  • Answer # 1

    If you want to decode a byte sequence, use the struct module.

    import struct
    data_hex = b '\ x02 \ x9b'
    data_dec, = struct.unpack ('>H', data_hex)
    print (data_dec)

  • Answer # 2

    print (data_hex [0] | (data_hex [1]<<8))

    What about


Related articles