5 python
我有一个我继承的python程序,我正在尝试扩展.
我已经将一个两字节长的字符串提取到一个名为pS的字符串中.
pS第一个字节是0x01,第二个是0x20,十进制值== 288
我一直试图将其值作为整数,我使用了表格的行
x = int(pS[0:2], 16) # this was fat fingered a while back and read [0:3]
Run Code Online (Sandbox Code Playgroud)
并得到消息
ValueError: invalid literal for int() with base 16: '\x01 '
Run Code Online (Sandbox Code Playgroud)
另一个C程序员和我一直在谷歌搜索并试图让这一整天工作.
请给我一些建议.
S.L*_*ott 20
查看struct模块.
struct.unpack( "h", pS[0:2] )
Run Code Online (Sandbox Code Playgroud)
对于带符号的2字节值.使用"H"表示未签名.
您可以将字符转换为它们的字符代码,ord然后以适当的方式将它们添加在一起:
x = 256*ord(pS[0]) + ord(pS[1])
Run Code Online (Sandbox Code Playgroud)