Converting UTF-16 QByteArray to QString

qt, unicode

Solution

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

Problem

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,

Original source

Related problems