Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting UTF-16 QByteArray to QString

Tags:

unicode

qt

I have a QByteArray which contains bytes in UTF-16 format.

A Java program sends data to a QT program via socket using

//dos is DataOutPutStream
dos.writeChars("hello world");

On the receiver side in QT program I read the data from socket into QByteArray and I want to convert it to a QString. inspecting the data variable of QByteArray it has 0h0e0l0l0o0 0w0o0r0l0d

When I try to make a QString out of it like this

QString str(byteArray)

The resulting string is empty perhaps because it encounters a 0 byte at the start and ofcouse because the documentation of the constructor I am using says that it internally uses fromAscii and what I am passing is not ascii.

I guess i have to somehow use QString::fromUTF-16 but that requires a ushort* and I have a QbyteArray.

Please advise what is the best way to do it.

Thanks,

like image 717
Ahmed Avatar asked Jul 01 '12 03:07

Ahmed


2 Answers

Get a pointer to the QByteArray.data() and cast it to ushort*

like image 136
Martin Beckett Avatar answered Sep 23 '22 01:09

Martin Beckett


This would work, assuming your utf-16 data is of the same endianness or has the BOM (Byte Order Mark):

QByteArray utf16 = ....;
auto str = QString::fromUtf16(
                reinterpret_cast<const ushort*>(utf16.constData()));
like image 32
Kuba hasn't forgotten Monica Avatar answered Sep 26 '22 01:09

Kuba hasn't forgotten Monica