Correct way to losslessly convert to and from std::string and QByteArray(无损转换 std::string 和 QByteArray 的正确方法)
问题描述
什么是在 std::string 和 QByteArray 之间无损转换的正确方法...主要是为了处理二进制数据?
What is the correct way to convert losslessly between std::string and QByteArray... mostly for the purpose of handling binary data?
我正在使用:
QByteArray qba = QString::fromStdString(stdString).toAscii();
和
QString(qba).toStdString();
但我想检查一下这是否真的正确.
but I wanted to check whether this is actually correct.
推荐答案
对于二进制数据,您的解决方案是有问题的,因为非 ASCII 字符会被 QString:: 转换为 .对于 '?'toAscii()QString 的内部表示,还有不必要的 UTF-16 转换开销.正如您可能已经猜到的那样,QString 仅应在数据是文本而非二进制数据时使用.
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.
QByteArray 和 std::string 都有原始数据(C 字符串 + 长度)的构造函数,也有转换为 C 字符串 + 长度的构造函数.因此您可以使用它们进行转换:
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());
它们都是二进制安全的,这意味着字符串可能包含 ' ' 字符并且不会被截断.数据也不会被触及(没有 UTF 转换),所以这种转换是无损"的.
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".
确保使用长度作为第二个参数的构造函数(对于 QByteArray 和 std::string),因为大多数其他构造函数会在之前截断数据第一次出现零.
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.
这篇关于无损转换 std::string 和 QByteArray 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无损转换 std::string 和 QByteArray 的正确方法
基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
