简体   繁体   English

如何将字符串2字节长转换为python中的整数

[英]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. 我有一个我继承的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. 请给我一些建议。

Look at the struct module. 查看struct模块。

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

For a signed 2-byte value. 对于带符号的2字节值。 Use "H" for unsigned. 使用“H”表示未签名。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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