简体   繁体   中英

How do I convert a string 2 bytes long to an integer in 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.

Look at the struct module.

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

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

您可以使用ord将字符转换为其字符代码,然后以适当的方式将它们一起添加:

x = 256*ord(pS[0]) + ord(pS[1])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM