【问题标题】:Treat NULL as character in QByteArray将 NULL 视为 QByteArray 中的字符
【发布时间】:2019-10-29 15:57:32
【问题描述】:

我正在使用 QT4.8,我需要将一个数组发送到另一个设备,其中包含一些 0x00 值。但是,QByteArray 将 0x00 值视为字符串的末尾。我想知道这是否可能,我正在努力实现什么。这是我的测试代码:-

zeroissue::zeroissue(QWidget *parent, Qt::WFlags flags)
    : QMainWindow(parent, flags)
{
    ui.setupUi(this);
    unsigned char zero = 0x00;
    QByteArray test;
    test.append("this is a test");
    test.append(zero);
    test.append("test complete");
    qDebug() << "test = " << test;
}

请建议我一种将0x00 视为 QByteArray 中的字符的方法。

【问题讨论】:

    标签: c++ qt qt4.8 qbytearray


    【解决方案1】:

    不知道有没有可能,

    是的,是的。来自QByteArray's documentation

    QByteArray 可用于存储原始字节(包括“\0”)和传统的 8 位“\0”结尾的字符串。

    以下main 函数按预期工作

    int main(int argc, char** argv)
    {
       char null_char = '\0';
       QByteArray test;
       test.append("this is a test");
       std::cout << "size(): " << test.size() << std::endl;
    
       test.append(null_char);
       std::cout << "size(): " << test.size() << std::endl;
    
       test.append("test complete");
       std::cout << "size(): " << test.size() << std::endl;
    
       return 0;
    }
    

    并产生以下预期输出:

    size(): 14
    size(): 15
    size(): 28
    

    当你使用

    qDebug() << "test = " << test;
    

    您应该会在输出中看到嵌入的空字符。请参阅https://doc.qt.io/qt-5/qdebug.html#operator-lt-lt-20 了解更多详情。

    【讨论】:

      猜你喜欢
      • 2016-08-24
      • 2020-07-06
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      • 2018-02-14
      • 2014-11-01
      • 1970-01-01
      • 2017-05-27
      相关资源
      最近更新 更多