How to convert QString with special characters into a byte stream to send it via Linux pipe

Viewed 353

I have a QString containing a special character (µ) encoded in UTF-8:

QString data = "197,45 \xc2\xb5m";

I need to send that string via a Linux pipe to another program. I tried to convert the string into something like this:

char msg[15];    
for(int i = 0; i < data.length(); i++) {
    msg[i] = data.toUtf8()[i];
}
msg[data.length()] = '\0';

I send msg to the pipe, but I only receive "197,45 µ", not "197,45 µm". I try to read the data on the read end with:

char data[15];
read(fd, data, nbytes);

I don't know much about character/string conversion, so I would be glad if you could explain how I should approach this problem. Thank you.

2 Answers

It is conceptually wrong to store UTF-8 encoded bytes in a QString. Use QByteArray for that, OR use QString::fromUtf8() to convert your UTF-8 string literals to a proper QString. To go back, use the qUtf8Printable macro or QString::toUtf8 to get a QByteArray.

What you are doing seems to be mainly "serializing the data" into a binary pipe, so an option that could make sense is to use a QDataStream which is designed for that purpose.

Something like:

QByteArray buffer;
QDataStream stream(&buffer, QIODevice::WriteOnly);

QString data = "197,45 \xc2\xb5m";
stream << data;

sendToPipe(buffer.constData(), buffer.size());

And the similar on the other side, using operator>> to read the data from the stream.

QByteArray buffer(dataPtr, size);
QDataStream stream(buffer);

QString data;
stream >> data;
Related