正确地从std :: string和QByteArray进行无损转换的正确方法 [英] Correct way to losslessly convert to and from std::string and QByteArray

查看:840
本文介绍了正确地从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.

QByteArraystd::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());

它们都是二进制安全的,这意味着字符串可能包含'\0'字符并且不会被截断.数据也不会被触及(没有UTF转换),因此这种转换是无损的".

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".

确保将长度作为第二个参数的构造函数(对于QByteArraystd::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进行无损转换的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆