Python – How to convert a string 2 bytes long to an integer in python

python

I have a python program I've inherited and am trying to extend.

I have extracted a two byte long string into a string called pS.

pS 1st byte is 0x01, the second is 0x20, decimal value == 288

I've been trying to get its value as an integer, I've used lines of the form

x = int(pS[0:2], 16)  # this was fat fingered a while back and read [0:3]

and get the message

ValueError: invalid literal for int() with base 16: '\x01 '

Another C programmer and I have been googling and trying to get this to work all day.

Suggestions, please.

Best Solution

Look at the struct module.

struct.unpack( "h", pS[0:2] )

For a signed 2-byte value. Use "H" for unsigned.