python 如何在python中将2字节长的字符串转换为整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/826284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I convert a string 2 bytes long to an integer in python
提问by sth
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.
建议,请。
回答by S.Lott
回答by sth
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])