Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

c++ - Correct way to losslessly convert to and from std::string and QByteArray

What is the correct way to convert losslessly between std::string and QByteArray... mostly for the purpose of handling binary data?

I'm using:

QByteArray qba = QString::fromStdString(stdString).toAscii();

and

QString(qba).toStdString();

but I wanted to check whether this is actually correct.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For binary data your solution is problematic since non-ASCII characters would be converted to '?' by QString::toAscii(). There is also the unnecessary overhead of UTF-16 conversion for the internal representation of QString. As you might have guessed, QString should only be used if the data is textual, not binary.

Both QByteArray and std::string have constructors for raw data (C-string + length) and also a conversion to C-string + length. So you can use them for conversion:

// std::string => QByteArray
QByteArray byteArray(stdString.c_str(), stdString.length());

// QByteArray => std::string
std::string stdString(byteArray.constData(), byteArray.length());

They are both binary-safe, meaning that the string may contain '' characters and doesn't get truncated. The data also doesn't get touched (there is no UTF conversion), so this conversion is "lossless".

Make sure to use the constructors with the length as the second argument (for both QByteArray and std::string), as most other constructors will truncate the data before the first occurrence of a zero.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...