Qt - Convert QString to Unicode QByteArray

I have a client-server application where the client will be in Qt (Ubuntu) and the server will be C #. The Qt client will send the strings in UTF-16 encoded format. I used the QTextCodec class to convert to UTF-16. But whenever a transformation occurs, it will be complemented by several characters. for instance

"<bind endpoint = '2_3' />"

will be changed to

"\ ff \ fe <\ 0b \ 0i \ 0n \ 0d \ 0 \ 0e \ 0n \ 0d \ 0p \ 0o \ 0i \ 0n \ 0t \ 0 = \ 0 '\ 02 \ 0_ \ 03 \ 0' \ 0 / \ 0> \ 0 \ 0 \ 0 "

I have the following code that converts a QString to a QByteArray

//'socketMessage' is the QString, listener is the QTcpSocket QTextCodec *codec = QTextCodec::codecForName("UTF-16"); QByteArray data = codec->fromUnicode(socketMessage); listener->write(data); 

I even tried QTextStream, QDataStream etc. for coding. But every time I get the same result. Am I something wrong here?

+4
source share
2 answers

Although the question was asked a long time ago, I had the same problem. The solution to this is to create a QTextEncoder with the QTextCodec :: IgnoreHeader option.

 QTextCodec *codec = QTextCodec::codecForName("UTF-16"); QTextEncoder *encoderWithoutBom = codec->makeEncoder( QTextCodec::IgnoreHeader ); QString str("Foobar") QByteArray bytes = encoderWithoutBom ->fromUnicode( s ); 

This will result in a QByteArray without specification.

+3
source

Initially, \ ff \ fe is the Unicode (BOM) byte order mark for UTF-16, little-endian. I'm not sure how to get QTextCodec to omit this, but if you want to get QByteArray from a string in UTF-16 without a specification, you can try the following:

 QString s("12345"); QByteArray b((const char*) (s.utf16()), s.size() * 2); 
+2
source

All Articles