Qt -轉換QString到Unicode QByteArray。

[英]Qt - Converting QString to Unicode QByteArray


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

我有一個客戶端-服務器應用程序,客戶端將在Qt(Ubuntu),服務器將是c#。Qt客戶端將以UTF-16編碼格式發送字符串。我已經使用QTextCodec類轉換為UTF-16。但是每當轉換發生時,它就會添加更多的字符。例如

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

“ <綁定端點= ' 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"

“\ ff \鐵< \ 0 b我\ \ 0 0 n \ 0 d \ \ 0 e \ n \ 0 d \ 0 p o \ \ 0 0 i \ n \ 0 t \ 0 = \ 0 ' \ 02 \ 0 _ \ 03 \ 0 ' \ 0 / \ 0 > \ \ 0 \ 0”

I have following code which converts the QString to QByteArray

我有以下代碼將QString轉換為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?

我甚至嘗試過QTextStream、QDataStream等進行編碼。但每次我都得到同樣的結果。我是不是做錯了什么?

2 个解决方案

#1


3  

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::IgnoreHeader創建一個QTextEncoder。

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.

這將導致沒有BOM的QByteArray。

#2


2  

The \ff\fe at the beginning is the Unicode byte order mark (BOM) for UTF-16, little-endian. I'm not sure how to get the QTextCodec to ommit that but if you want to get a QByteArray from a string in UTF-16 without the BOM you could try this:

開始的\ff\fe是UTF-16, little-endian的Unicode字節順序標記(BOM)。我不知道如何讓QTextCodec進入ommit但是如果你想從UTF-16的字符串中得到QByteArray如果沒有BOM,你可以試試這個:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/08/30/7212764d18cfee69b0dfb6e150b10ff4.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com