简体   繁体   中英

Convert multibyte character array to QChar array

I have two buffers (example sizes):

char c[512];
QChar q[256];

Assuming 'c' contains multibyte character string (UTF-8). I need to convert it to QChar sequence and place it in 'q'. I guess a good example of what I need could be MultiByteToWideChar function.
IMPORTANT: this operation shall not involve any explicit or implicit memory allocations, except for additional allocations on the stack, maybe. Please, do not answer if you are not sure what the above means.

QChar contains an ushort as only member, so its size is sizeof(ushort) .

In QString context it represents UTF-16 'characters' (code points).

So it's all about encoding here.

If you know your char const * is UTF-16 data in the same endianness / byte order as your system, simply copy it:

memcpy(q, c, 512);

If you want to initialize a QString with your const char * data, you could just interpret it as UTF-16 using QString::fromRawData() :

QString strFromData = QString::fromRawData(reinterpret_cast<QChar*>(c), 256);
// where 256 is sizeof(c) * sizeof(char) / sizeof(QChar)

Then you don't even need the QChar q[256] array.

If you know your data is UTF-8 , you should use QString::fromUtf8() and then simply access its inner memory with QString::constData() .

Using QString with UTF-8 I don't know of any method to completely prevent heap allocations. But the mentioned way should only allocate twice: Once for the PIMPL of QString , once for the UTF-16 string data.


If your input data is encoded as UTF-8 , the answer is No : You cannot convert it using Qt.

Proof: Looking at the source code of qtbase/src/corelib/codecs/qutfcodec.cpp we see that all functions for encoding / decoding create new QString / QByteArray instances. No function operates on two arrays as in your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM