python - 将python字节 "array"转换为int“数组

标签 python

这是我在 python 中的第一个代码,我有这个问题:

我正在阅读一个二进制文件:

def read_file(file):
    with open(file, "rb") as f:
        frame = f.read()
        print(type(frame)) #out = <class 'bytes'>
        return frame

我需要将所有向量转换为 int 值,而不是将它们用作字节。

打印后我得到这样的东西:
print(frame[0:10])
b'\xff\xff\xff\xffXabccc'

但是,如果我只打印通过一个位置,我会得到这个:(整数值是正确的,但我只是使用函数打印来获取它们)
print(frame[0])
255    
print(frame[1])
255
print(frame[2])
255
print(frame[3])
255
print(frame[4])
88
print(frame[5])
97
print(frame[6])
98
print(frame[7])
99
print(frame[8])
99
print(frame[9])
99
print(frame[10])
98

问题是:如何一步转换数组的所有位置?我想运行代码
print(frame[0:10])

并得到类似的东西
[255, 255, 255, 255, 88, 97, 98, 99 ,99, 99, 98]

最佳答案

注意:此解决方案仅适用于 Python 3。对于 Python 2 解决方案,请参阅 Scott Hunter 的回答。

您可以使用 list comprehension 来做到这一点。 :

In [1]: frame = b'\xff\xff\xff\xffXabccc'

In [2]: int_values = [x for x in frame]

In [3]: print(int_values)
[255, 255, 255, 255, 88, 97, 98, 99, 99, 99]

要确认这些确实存储为您可以使用的整数值:
In [4]: print([type(x) for x in int_values])
[<class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>, 
<class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>, <class 'int'>]

关于python - 将python字节 "array"转换为int“数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48988266/

相关文章:

python - 找到多米诺骨牌顺序的有效方法

python - 使用 VSCode 在 Python 中调试期间读取输入

python - 我可以在一个月中的某一天进行 order_by 吗?

python - 从文本文件的数据中计算平均值

python - python中物理量的命名

python - 使用 Python 在优化曲线上找到 "elbow point"

python - 如何在 Azure VM(或类似虚拟机)中运行图形自动化

Python Websocket 模块继续启动未被杀死的进程,导致内存问题

javascript - 加载更多功能或无限分页

python - 受监控的培训类(class)如何运作?