QBitArray到QByteArray

时间:2012-01-08 08:21:08

标签: c++ qt qbytearray

当我们使用此文本“ali ata bak”创建文本文件时,我们将此文件用作程序的输入。代码正常运行。但是当我们在文本文件中输入“1111111111111111111111”这个文本时,Code没有运行预期。那么问题是什么?

#include <QtCore/QCoreApplication>
#include <QBitArray>
#include <QByteRef>
#include <QFile>
#include <iostream>
#include <stdlib.h>
#include <QTextStream>

// Buffer Size #num of KB's
#define BUFFER_SIZE_KB 1

// Do not change !!
#define BUFFER_SIZE_BYTE BUFFER_SIZE_KB*1024
#define BUFFER_SIZE_BIT  BUFFER_SIZE_BYTE*8

using namespace std;


QBitArray bytesToBits(QByteArray bytes) {
    QBitArray bits(bytes.count()*8);
    // Convert from QByteArray to QBitArray
    for(int i=0; i<bytes.count(); ++i)
        for(int b=0; b<8; ++b)
            bits.setBit(i*8+b, bytes.at(i)&(1<<b));
    return bits;
}


QByteArray bitsToBytes(QBitArray bits) {
    QByteArray bytes;
    bytes.resize(bits.count()/8);
    // Convert from QBitArray to QByteArray
    for(int b=0; b<bits.count(); ++b)
        bytes[b/8] = ( bytes.at(b/8) | ((bits[b]?1:0)<<(b%8)));
    return bytes;
}


int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QString inFilename;
    QString outFilename;
    QTextStream qtin(stdin);


    cout << "Filename : ";
    qtin >> inFilename;
    outFilename.append("_");
    outFilename.append(inFilename);

    QFile infile(inFilename);
    if (!infile.open(QIODevice::ReadOnly)) {
        cout << "\nFile cant opened\n";
        system("pause");
        return 1;
    }

    QFile outfile(outFilename);
    if (!outfile.open(QIODevice::WriteOnly)) {
        cout << "\nFile cant opened\n";
        system("pause");
        return 2;
    }

    QByteArray bytes, bytes2;
    QBitArray bits;


    while ((bytes = infile.read(BUFFER_SIZE_BYTE)) >0 ) {

        bits = bytesToBits(bytes);
        bytes2 = bitsToBytes(bits);// PROBLEM IS HERE
        outfile.write(bytes2);

    }

    outfile.close();
    infile.close();
    cout << "Finished\n";
    return a.exec();
}

4 个答案:

答案 0 :(得分:7)

初始化问题。

QByteArray bitsToBytes(QBitArray bits) {
    QByteArray bytes;
    bytes.resize(bits.count()/8+1);
    bytes.fill(0);
    // Convert from QBitArray to QByteArray
    for(int b=0; b<bits.count(); ++b)
        bytes[b/8] = ( bytes.at(b/8) | ((bits[b]?1:0)<<(b%8)));
    return bytes;
}

这会产生正确的答案

答案 1 :(得分:0)

您可能还想阅读维基百科http://en.wikipedia.org/wiki/Endianness

中的字节顺序

答案 2 :(得分:0)

QByteArray bitsToBytes(const QBitArray& bits)
{
    QByteArray bytes;
    QDataStream stream(&bytes, QIODevice::WriteOnly);
    stream << bits;
    return bytes;
}

答案 3 :(得分:0)

QBitArray bits(8);

// The deep copy of bits
QByteArray bytes(bits.bits(), bits.count() / 8); 
--------------------------------------------------------------------------
// The bits are not copied
QByteArray bytes = QByteArray::fromRawData(bits.bits(), bits.count() / 8);