Qt:<bool> QVector to QByteArray

Qt: QVector<bool> to QByteArray

本文关键字:QVector to QByteArray gt bool lt Qt      更新时间:2023-10-16

你好,请帮我转换。布尔到字节数组的QVector。

QByteArray currentArray
//get(currentArray); currentArray is just text.
QMap <QChar, QVector<bool> > table;
//creating table;
//table: is set of QChar and bit code
//0: 100110111001
//1: 00011
//2: 011110
//3: 010001
//...
QByteArray compressedArray;
//converting QVector<bool> from QMap to QByteArray
//it do not work fine.
int count=0;
Сhar buf=0;
i=0;
while(i<currentArray.size())
{
    QVector <bool> x = table[currentArray.at(i++)];
    for(int n=0; n < x.size(); n++)
    {
        buf = buf | x[n] << (7 - count);
        count ++;
        if (count == 8)
        {
            count=0;
            compressedArray += buf;
            buf = 0;
        }
    }
}

这是霍夫曼算法的一个实现。解密工作正常,所以问题就在这里。

我不能说你的问题的确切原因是什么,但你的代码中有几个问题可能会导致问题:

QVector <bool> x = table[currentArray.at(i++)];
  1. currentArray.at()返回的char被隐式转换为QChar-对于值>127,这可能是一个问题,查找错误的值,这取决于查找是如何创建的。=>更好地使用QMap甚至QVector,其中256个条目具有char作为索引,这要快得多。

  2. 如果键不存在,则表[…]将向映射插入一个新的空条目。我不认为这是这里的意图-最好使用table.value().

我也不记得了,但我认为huffman存储的比特从比特0开始,然后填充到最高有效比特,所以也许

 buf = buf | x[n] << (7 - count);

应该反过来吗?

祝你好运。