如何使用 Python 阅读未签名的短裤?
How can I read unsigned shorts using Python?
主要问题
我想了解如何在 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,)]
相关文章:
- 如何使用Python从C++中读取谷物序列化数据
- 使用 Python Extension API 包装复杂C++类
- 是否可以使用 Python csv 阅读器读取使用 C++ std::setw 生成的文件?
- 如何构建一个 setup.py 来编译C++使用 Python、pybind11 和 Mingw-w64 的扩展?
- 无法使用 python ctypes 加载C++共享库
- 使用 python 或 c ++ 中的 sql 根据输入数据输出输出示例
- 使用 Python 事件并与 C++ 交互
- 使用 Python 和正则表达式提取源代码中的C++注释
- 使用 Python 导出 4 个字节浮点数
- 如何创建一个接口,允许我访问C++中的按钮(和其他ui)函数,该函数是使用python中的MFC实现的
- 如何使用 python 调用 c++ 函数
- 如何使用python运行Hello world c ++代码
- Qt Designer使用Python 3.5而不是Python 3.7
- 使用 Python、ROS 和 C++ 进行日志记录
- 如何使用 Python 阅读未签名的短裤?
- 使用 python 绑定来检查 C++ 类型是否是规范方式的指针、引用等?
- 使用python预处理后,C++(opencv)中的垫子类型数据与image_to_array相同
- 使用 python 胶囊在 cython 和 pybind11 之间传输 c++ 对象
- 如何使用 python 从C++标头中检索类名及其方法名
- 如何在C ++(qt)代码中使用python脚本?(网页抓取方面)