【问题标题】:How can I read unsigned shorts using Python?如何使用 Python 阅读未签名的短裤?
【发布时间】:2017-07-10 09:16:30
【问题描述】:

主要问题

我想了解如何在 Python 中读取 C++ unsigned short。我试图使用np.fromfile('file.bin',np.uint16),但它似乎不起作用。将此作为主要问题。

案例研究:

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

标题:

QVector<unsigned short> rawData;

ma​​in.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 阅读它,但我找不到如何阅读无符号短裤。来自literature 的无符号短裤应该是 2 个字节,所以我尝试使用以下方法读取它:

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

但是,如果我将读取它的单个 unsigned_value 与 python 进行比较,并使用 C++ 将其打印为字符串:

Qstring single_value = QString::number(unsigned_value)

它们是不同的。

【问题讨论】:

标签: python c++ qt numpy


【解决方案1】:

我会尝试结束性。试试'&lt;u2''&gt;u2'

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

'&gt;' 反转 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'

【讨论】:

    【解决方案2】:

    rawOut.writeRawData((char *) &amp;rawData, 2*rawData.size()); 正在您的文件中写入大量垃圾。 QVector 不能像您尝试的那样直接转换为 short 数组。

    使用下面的代码来写你的数据

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

    【讨论】:

    • 谢谢,但我必须写一个整个数组而不是单个值。
    • @GM 是的,它写入了一个完整的数组
    • 它不起作用它说 ISO c++ 禁止声明 'singleVal'
    • 旧编译器...用foreach(const unsigned short&amp; singleVal, rawData)替换for(const auto&amp; singleVal : rawData)
    【解决方案3】:

    看看struct module

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

    示例输出:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-17
      • 1970-01-01
      • 2021-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多