PDA

View Full Version : QByteArraty to QString different size bug?



Coder5546
22nd December 2012, 16:56
Hi, tell me what i`m doing wrong, or it is a bug?



long buffer = 1048576;
QByteArray array = file.read(buffer);
QString b(array);
qDebug()<< array.length(); // result 1048576
qDebug()<< b.length(); // result 6


Why different length? I`m testing on few files

Santosh Reddy
22nd December 2012, 17:46
It all depends on file contents, I don't think there is anything wrong with this code and result

Coder5546
22nd December 2012, 18:00
Then let see, when the buffer is the file size, and i`m reading all to QByteArray next using QString put into readed QByteArray . Write this QString to file u have 2 different files. Why?



long buffer = 1048576; // size file
QByteArray array = file.read(buffer);
QString b(array);
qDebug()<< array.length(); // result 1048576
qDebug()<< b.length(); // result 6
qDebug()<< b.toUtf8().length(); // result 6
file2.write(b.toUtf8();

wysota
22nd December 2012, 19:29
I think it is safe to assume the 7th byte of the byte array is \0.

anda_skoa
23rd December 2012, 17:11
One curious thing in the example code is that, assuming Qt4, it uses QString::fromLatin1() for the "read" conversion and toUtf() for the "write" conversion.

Cheers,
_

wysota
23rd December 2012, 22:14
Another curious thing is that if the byte array represents text, there should be no null bytes there for both latin1 and utf-8.

Coder5546
25th December 2012, 20:29
I think it is safe to assume the 7th byte of the byte array is \0.
Indeed

But im using another way, so thanks all for answers and helping



long buffer = 1048576; // size file
QByteArray array = file.read(buffer).toBase64();//changed
QString b(array);
qDebug()<< array.length(); // result 1048576
qDebug()<< b.length(); // result 1048576

ChrisW67
25th December 2012, 22:13
If you read 1048576 bytes from a file (line 2) and then Base64 (http://en.wikipedia.org/wiki/Base64) encode them (also line 2) the resulting string is not 1048576 characters long (line 5). The Base64 output string will have four characters for every three bytes (or part thereof) in the input.

If it's not a file containing data representing Latin-1 or UTF-8 encoded strings then why put it in a QString at all? What are you actually trying to achieve?

Coder5546
25th December 2012, 23:08
If you read 1048576 bytes from a file (line 2) and then Base64 (http://en.wikipedia.org/wiki/Base64) encode them (also line 2) the resulting string is not 1048576 characters long (line 5). The Base64 output string will have four characters for every three bytes (or part thereof) in the input.

If it's not a file containing data representing Latin-1 or UTF-8 encoded strings then why put it in a QString at all? What are you actually trying to achieve?

I'm using this for send emial with attachment using smtp, and i need convert to Base64. Works fine