【问题标题】:Qt5 convert chars to 8bits unsigned valuesQt5 将字符转换为 8 位无符号值
【发布时间】:2016-04-12 06:48:34
【问题描述】:

我有两种方法可以将字符转换为它们代表的 8 位字节值。在第一个中它给出了正确的答案,但在第二个中它给出了一个额外的 0,所以我不得不ba.size()-1。 我的问题是为什么我必须在第二个中这样做?我知道这很可能是 /0 终止符。如果我没有错?还有没有更好的方法来做到这一点?

    // very simple test if we can take bytes and get them in decimal (0-255)format:
    QByteArray ba("down came the glitches and burnt us in ditches and we slept after we ate our dead...");
    for (int i = 0; i < ba.size(); ++i)
    qDebug() << "Bytes are: "<< static_cast<quint8>(ba[i]);
    // very simple second way to do it...
    int j = 0;
    while (j < ba.size()-1){
    qDebug() << "Bytes are: "<< static_cast<quint8>(ba[++j]);
}

【问题讨论】:

  • 两种方式不应该有相同的确切结果吗?如果不清楚的话,这是主要问题......

标签: c++ qt qbytearray


【解决方案1】:

差异是因为增量操作的使用无效。当您使用++j 时,您已经拥有1 的值,因此您永远不会获得0 索引。你也得到最后一个索引大于数组大小。正确的做法是:

qDebug() << "Bytes are: "<< static_cast<quint8>(ba[j++]);

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 2013-06-08
    相关资源
    最近更新 更多