5

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.

1
  • Could youplease show the output of: "print pS"? It's unclear to me why int(pS[0:3], 16) won't work. Do you not have the "0x" prefix? Commented May 5, 2009 at 18:49

4 Answers 4

22

Look at the struct module.

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

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

Sign up to request clarification or add additional context in comments.

Comments

5

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])

Comments

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

But it will be in array form

struct.unpack( "h", pS[0:2] )[0] this will get the value direct

Comments

0

This is a big-endian two-byte number. If you don't want to use the struct module, you can also use int. If the input is of type str, you'll need to convert it to a bytes instance using bytes(pS, 'utf-8') first though.

num = int.from_bytes(pS, 'big')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.