将字节转换为整数的 Python 2 和 3 兼容方法

标签 python python-3.x python-2.x

我有一个类似于下面的字节串。

foo = b"\x00\xff"

我想将 foo 每个十六进制值转换为整数。我可以在 Python 3 中使用以下内容。

In [0]: foo[0]
Out[0]: 0  
In [1]: foo[1]
Out[1]: 255  

Python 2 需要调用 ord()

In [0]: ord(foo[0])
Out[0]: 0  
In [1]: ord(foo[1])
Out[1]: 255  

有没有一种好的方法可以在必须同时适用于 Python 2 和 3 的代码中编写此代码? six 包有一个 six.byte2int() 函数,但它不起作用,因为它只查看第一个字节和 six.byte2int(foo[0 ] 在 Python 3 上失败,因为 foo[0] 在 Python 3 中是一个整数。

有没有比 if six.PY2 分支更好的选择?

最佳答案

你有三个选择:

  • 使用 bytearray() :

    ba = bytearray(foo)
    ba[0]
    
  • 使用 struct module将字节解压缩为整数:

    import struct
    struct.unpack('{}B'.format(len(foo)), foo)
    
  • 使用 array module按顺序将字节解压缩为整数:

    import array
    array.array('B', foo)
    

演示(Python 2.7):

>>> import struct, array
>>> foo = b"\x00\xff"
>>> list(bytearray(foo))
[0, 255]
>>> struct.unpack('{}B'.format(len(foo)), foo)
(0, 255)
>>> array.array('B', foo)
array('B', [0, 255])

演示(Python 3.4):

>>> import struct, array
>>> foo = b"\x00\xff"
>>> list(bytearray(foo))
[0, 255]
>>> struct.unpack('{}B'.format(len(foo)), foo)
(0, 255)
>>> array.array('B', foo)
array('B', [0, 255])

关于将字节转换为整数的 Python 2 和 3 兼容方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26121553/

相关文章:

python - 组织大型 Django 项目的指南

Python unittest 分支覆盖似乎错过了 zip 中执行的生成器

regex - 避免在正则表达式中转义字符

python-3.x - 如何从 faust 应用程序向 Websocket 发送数据

Python2 datetime - 将纪元时间转换为带偏移量的 UTC 时间戳

javascript - Flask 中的 render_template on JS 点击事件

python - 在 gunicorn 进程中共享一个 numpy 数组

python-3.x - 通过更改 pandas 中的组内的列值来创建组

Python 2.x 排序难题

python - 在 Python unicode 字符串中删除重音(规范化)的最佳方法是什么?