I have a python program I've inherited and am trying to extend.
我有一个我继承的python程序,我正在尝试扩展。
I have extracted a two byte long string into a string called pS.
我已经将一个两字节长的字符串提取到一个名为pS的字符串中。
pS 1st byte is 0x01, the second is 0x20, decimal value == 288
pS第一个字节是0x01,第二个是0x20,十进制值== 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.
另一个C程序员和我一直在谷歌搜索并试图让这一整天工作。
Suggestions, please.
2 个解决方案
#1
Look at the struct module.
查看struct模块。
struct.unpack( "h", pS[0:2] )
For a signed 2-byte value. Use "H" for unsigned.
对于带符号的2字节值。使用“H”表示未签名。
#2
You can convert the characters to their character code with ord
and then add them together in the appropriate way:
您可以使用ord将字符转换为字符代码,然后以适当的方式将它们一起添加:
x = 256*ord(pS[0]) + ord(pS[1])
#1
Look at the struct module.
查看struct模块。
struct.unpack( "h", pS[0:2] )
For a signed 2-byte value. Use "H" for unsigned.
对于带符号的2字节值。使用“H”表示未签名。
#2
You can convert the characters to their character code with ord
and then add them together in the appropriate way:
您可以使用ord将字符转换为字符代码,然后以适当的方式将它们一起添加:
x = 256*ord(pS[0]) + ord(pS[1])