Correct way to losslessly convert to and from std::string and QByteArray
Solution 1
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 '\0'
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.
Solution 2
As of Qt 5.4, QByteArray
has built in support for std::string
conversions via QByteArray::toStdString()
and QByteArray::fromStdString()
.
These are implemented almost identically to leemes' answer.
inline std::string QByteArray::toStdString() const
{ return std::string(constData(), length()); }
inline QByteArray QByteArray::fromStdString(const std::string &s)
{ return QByteArray(s.data(), int(s.size())); }
Jake Petroules
Software developer primarily self taught since age 12. Experience in design and development of computer programs, websites, and database systems, 3D graphics, UI design and usability, cross-platform development, and open source software. Co-founded a software company (Petroules Corporation) in college which developed data security software (Silverlock). Active developer in the Open Source Qt Project (qt.io) from late 2012 to early 2018. Key contributor to the Qbs (pronounced "Cubes") build system since its early history. Worked at The Qt Company from late 2015 to early 2018. Working at Apple in the Developer Tools team (Xcode, llbuild, etc.) since February 2018. Studied computer science at Keene State College and took courses at the Massachusetts Institute of Technology and online courses through Stanford University. Specialties: C, C++, Objective-C, Swift, macOS, iOS, Xcode, build automation, cross-platform, qbs, Qt, security & cryptography, UX and UI design
Updated on September 07, 2020Comments
-
Jake Petroules over 3 years
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.