tags:

views:

311

answers:

2

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.

+14  A: 

Look at the struct module.

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

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

S.Lott
+3  A: 

You can convert the characters to their character code with ord and then add them together in the appropriate way:

x = 256*ord(pS[0]) + ord(pS[1])
sth
Many, many thanks! This did it!