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

标签 python

我有一个我继承的 python 程序,正在尝试扩展。

我已经将一个两字节长的字符串提取到一个名为 pS 的字符串中。

pS 第一个字节是0x01,第二个字节是0x20,十进制值== 288

我一直在尝试获取它的整数值,我使用了以下形式的行

x = int(pS[0:2], 16)  # this was fat fingered a while back and read [0:3]

获取消息

ValueError: invalid literal for int() with base 16: '\x01 '

另一位 C 程序员和我一直在谷歌搜索并试图让它工作一整天。

请提出建议。

最佳答案

查看struct模块。

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

对于带符号的 2 字节值。使用“H”表示无符号。

关于python - 如何将 2 个字节长的字符串转换为 python 中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/826284/

相关文章:

python - Tensorflow 更改输出图像大小以不同于训练输入大小

java - 将 Java Google AppEngine 应用程序转换为 Python AppEngine

Python:递归删除空文件夹

python - 谷歌云应用引擎 : Python2 or Python3? 的最佳实践

python - 如何让 optparse 的 OptionParser 忽略无效选项?

python - 使用 pandas 过滤数据

python - 如何组织Python源代码文件?

javascript - 将 Javascript 生成的表上的 <td> 值抓取到 Python

python - 卸载 Ubuntu 18.04 中具有多个 python 版本的所有 Python 包

python - 资源的 getChild 没有调用扭曲