Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - Converting QString to Unicode QByteArray

Tags:

unicode

qt

I have a client-server application where client will be in Qt(Ubuntu) and server will be C#. Qt client willsend the strings in UTF-16 encoded format. I have used the QTextCodec class to convert to UTF-16. But whenever the conversion happens it will be padded with some more characters. For example

"<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 following code which converts the QString to QByteArray

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

I have even tried the QTextStream,QDataStream etc for encoding. But everytime I end up with the same result. Am I doing something wrong here?

like image 472
user435152 Avatar asked Aug 30 '10 17:08

user435152


People also ask

How do you convert QString to hex in Qt?

Try QString::toInt, QString::toUInt, QString::toLong etc., for example: The second argument is the base, 16 in this case for hexadecimal. This solution will work if your string fits into a unsigned long long or shorter - it will not work if you want to convert arbitrarily long strings that way.

What is fromutf8?

UTF-8 is a variable-width character encoding used for electronic communication. Defined by the Unicode Standard, the name is derived from Unicode (or Universal Coded Character Set) Transformation Format – 8-bit. UTF-8.


1 Answers

Though the question is asked long ago, I had the same problem. The solution to it is to create an QTextEncoder with the option QTextCodec::IgnoreHeader.

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 BOM.

like image 129
gamecreature Avatar answered Sep 28 '22 13:09

gamecreature