當我們用這個文本「ali ata bak」創建一個文本文件時,我們使用這個文件作爲程序的輸入。代碼正常運行。但是當我們在文本文件中輸入「1111111111111111111111」這個文本時,代碼沒有運行。那麼問題是什麼?QBitArray到QByteArray
#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();
}
字節序你所說的「意外」的意思是什麼?請描述你所看到的以及你的期望。 – Mat 2012-01-08 08:24:37
輸出文件必須與輸入相同,但文本「11111」不相同 – sivanzor 2012-01-08 08:27:23