当我们创建带有“ali ata bak”文本的文本文件时,我们将该文件用作程序的输入。该代码正在正常运行。但是,当我们在文本文件中输入“1111111111111111111111”时,代码就不会正常运行。那是什么问题呢?
#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();
}
最佳答案
初始化问题。
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;
}
这会产生正确的答案
关于c++ - QBitArray到QByteArray,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8776261/