简体   繁体   English

Qt:QVector <bool> 到QByteArray

[英]Qt: QVector<bool> to QByteArray

Hello please help me with convertion. 您好,请帮我转换。 QVector of bool to array of bytes. 布尔的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;
        }
    }

}

This is an implementation of the algorithm Huffman. 这是霍夫曼算法的一种实现。 Decryption works correctly, so problem is here. 解密工作正常,所以问题出在这里。

I can't say what the exact cause of your problem is but there are several issues in your code that could cause problems: 我无法说出问题的确切原因是什么,但是代码中有几个问题可能会导致问题:

QVector <bool> x = table[currentArray.at(i++)];
  1. a char returned by currentArray.at() is implicitly converted to a QChar - for values > 127 this might be a problem and lookup the wrong value, this depends how the lookup was created. 由currentArray.at()返回的char被隐式转换为QChar-对于值> 127,这可能是一个问题,并且查找错误的值,这取决于创建查找的方式。 => better use QMap or even QVector with 256 entries having char as index which is much faster. =>最好使用QMap甚至QVector或带有char作为索引的256个条目的QVector,这要快得多。

  2. table[...] will insert a new empty entry to the map if no one exists for the key. 如果该键不存在,则table [...]将在地图上插入一个新的空条目。 I don't think this is intended here - better use table.value(). 我认为这不是要在这里使用的-最好使用table.value()。

Also I don't remember but I think huffman stores bits starting at bit 0 and then filling up to most significant bits, so maybe 另外我不记得了,但我认为霍夫曼存储从位0开始的位,然后填充到最高有效位,所以也许

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

should be the other way round? 应该反过来吗?

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM