Ahmed
Ahmed

Reputation: 15029

Converting UTF-16 QByteArray to QString

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,

Upvotes: 5

Views: 9745

Answers (2)

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()));

Upvotes: 3

Martin Beckett
Martin Beckett

Reputation: 96119

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

Upvotes: 4

Related Questions