2012-07-01 178 views
3

我有一個QByteArray中包含在UTF-16格式字節。轉換UTF-16的QByteArray到的QString

的Java程序通過使用

//dos is DataOutPutStream 
dos.writeChars("hello world"); 

在接收機端QT程序,我讀了插座數據到的QByteArray插座將數據發送到QT計劃,我想將其轉換爲QString。檢查的QByteArray的數據變量有0h0e0l0l0o0 0w0o0r0l0d

當我嘗試做的QString,它像這樣

QString str(byteArray) 

結果字符串是空的可能是因爲它在開始和ofcouse遇到0字節因爲我使用的構造函數的文檔說它在內部使用fromAscii,而我傳遞的不是ascii。

我想我必須以某種方式使用QString :: fromUTF-16,但需要一個USHORT *和我有一個QByteArray中。

請指教一下是做的最好的方式。

感謝,

回答

4

獲得一個指向QByteArray.data()然後將其丟至USHORT *

+0

確定該功能工作,但沒有得到正確的QString。它包含有線十六進制數字 – Ahmed

+1

字節排序問題? –

+0

我不知道在QByteArray中的數據是一樣的東西0h0e0l0l0o0 0w0o0r0l0d - 公告不存在在年底沒有空字符內,所以,我手動在的QString :: fromUTF-8指定尺寸爲第二PARAM但同樣的事情。我的平臺在Windows 7 – Ahmed

2

這會工作,假設你的UTF-16的數據是相同的字節順序的:

QByteArray utf16 = ....; 
QString str = QString::fromUtf16(
       reinterpret_cast<const ushort*>(utf16.constData())); 

如果你需要轉換字節序,這是做到這一點的一種方法:

QByteArray utf16 = ....; 
QDataStream ds(&utf16, QIODevice::ReadOnly); 
Q_ASSERT(utf16.count() % 2 == 0); 
QVector<ushort> buf(utf16.count()/2 + 1); 
int n = 0; 
ds.setByteOrder(QDataStream::BigEndian); 
while (!ds.atEnd()) { 
    ushort s; 
    ds >> s; 
    buf[n++] = s; 
} 
buf[n] = 0; 
QString str = QString::fromUtf16(buf.constData());