c++ - Qt5 将字符转换为 8 位无符号值

标签 c++ qt qbytearray

我有两种方法可以将字符转换为它们代表的 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]);
}

最佳答案

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

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

关于c++ - Qt5 将字符转换为 8 位无符号值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34662609/

相关文章:

c++ - 以编程方式忽略 Cout

c++ - 运算符重载困惑C++

c++ - 随机段错误?

c++ - Qt QString 十六进制值到 QByteArray

c++ - 使用assimp的骨骼动画中的矩阵顺序

c++ - 通过样式表识别特定的 QTabWidget 标签

linux - X 服务器触发(minval > maxval)

c++ - 将 QByteArray 从大端转换为小端

c++ - QDataStream 和 quint16 序列化怪异

c++ - 正确处理 SSL_shutdown