QBitArray for QByteArray

When we create a text file with this text "ali ata bak", and we use this file as input for the program. The code is working fine. But when we enter "111111111111111111111111" this text in a text file, the code does not work. So what is the problem?

#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();
}
+7
source share
3 answers

The initialization problem.

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;
}

it gives the correct answer

+8
source

You can also read content information from Wikipedia http://en.wikipedia.org/wiki/Endianness

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

All Articles