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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:55:52  来源:igfitidea点击:

How do I convert a string 2 bytes long to an integer in python

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

Look at the structmodule.

查看struct模块。

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

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

对于有符号的 2 字节值。使用“H”表示未签名。

回答by sth

You can convert the characters to their character code with ordand then add them together in the appropriate way:

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

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