如何使用 Python 阅读未签名的短裤?

How can I read unsigned shorts using Python?

本文关键字:何使用 Python      更新时间:2023-10-16

主要问题

我想了解如何在 Python 中阅读C++无符号的短篇。我试图使用np.fromfile('file.bin',np.uint16)但似乎不起作用。将此作为主要问题。

个案研究:

为了给更多的比赛 我有一个使用 QT C++和QDataStream方法导出为二进制文件的unsigned shorts数组。

页眉:

QVector<unsigned short> rawData;

主.cpp

QFile rawFile(QString("file.bin"));
rawFile.open(QIODevice::Truncate | QIODevice::ReadWrite);
QDataStream rawOut(&rawFile);
rawOut.writeRawData((char *) &rawData, 2*rawData.size());
rawFile.close();

我正在尝试使用 Python 和 numpy 阅读它,但我找不到如何阅读未签名的短裤。从文献中,无符号的短裤应该是 2 个字节,所以我尝试使用以下方法阅读它:

import numpy as np
np.readfromfile('file.bin',np.uint16)

但是,如果我将单个unsigned_value与python进行比较,并使用C++将其作为字符串进行导入:

Qstring single_value = QString::number(unsigned_value)

他们是不同的。

我会尝试结束性。尝试'<u2''>u2'

https://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html

'>'颠倒了 2 个字节的顺序

In [674]: np.array(123, np.dtype('>u2')).tostring()
Out[674]: b'x00{'
In [675]: np.array(123, np.dtype('<u2')).tostring()
Out[675]: b'{x00'
In [678]: np.array(123, np.uint16).tostring()
Out[678]: b'{x00'
rawOut.writeRawData((char *) &rawData, 2*rawData.size());

在你的文件中写入了大量的垃圾。QVector 不能像您尝试的那样直接投射到一组short

使用以下代码写入数据

for(const auto& singleVal : rawData)
rawOut << singleVal;

看看结构模块

import struct
with open('file.bin', 'rb') as f:
unsigned_shorts = struct.iter_unpack('H', f.read())
print(list(unsigned_shorts))

示例输出:

>>>[(1,), (2,), (3,)]