Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QByteArray to QString

I'm having issues with QByteArray and QString.

I'm reading a file and stores its information in a QByteArray. The file is in unicode, so it contains something like: t\0 e\0 s\0 t\0 \0 \0

I'm trying to compare this value to my specified value, but it fails, because in the debugger I see it's not an unicode string.

The code will explain everything:

QByteArray Data; //contains unicode string "t\0 e\0 s\0 t\0 \0 \0"
QString myValue = "test"; //value to compare.
if(Data.contains(myValue))
    //do some stuff.
else
    //do other stuff.

In the debugger, it shows me that the variable Data has the value "t\0 e\0 s\0 t\0 \0 \0" and myValue has the value "test". How can I fix it?

like image 990
Nika Avatar asked Jan 02 '13 23:01

Nika


People also ask

How do you convert QString to string?

You can use: QString qs; // do things std::cout << qs. toStdString() << std::endl; It internally uses QString::toUtf8() function to create std::string, so it's Unicode safe as well.


3 Answers

You can use this QString constructor for conversion from QByteArray to QString:

QString(const QByteArray &ba)

QByteArray data; QString DataAsString = QString(data); 
like image 133
Link H. Avatar answered Sep 22 '22 14:09

Link H.


You can use QTextCodec to convert the bytearray to a string:

QString DataAsString = QTextCodec::codecForMib(1015)->toUnicode(Data); 

(1015 is UTF-16, 1014 UTF-16LE, 1013 UTF-16BE, 106 UTF-8)

From your example we can see that the string "test" is encoded as "t\0 e\0 s\0 t\0 \0 \0" in your encoding, i.e. every ascii character is followed by a \0-byte, or resp. every ascii character is encoded as 2 bytes. The only unicode encoding in which ascii letters are encoded in this way, are UTF-16 or UCS-2 (which is a restricted version of UTF-16), so in your case the 1015 mib is needed (assuming your local endianess is the same as the input endianess).

like image 35
BeniBela Avatar answered Sep 25 '22 14:09

BeniBela


You can use:

QString::fromStdString(byteArray.toStdString())
like image 34
Tarek.Mh Avatar answered Sep 22 '22 14:09

Tarek.Mh