[英]How to convert QByteArray to a byte string?
I have a QByteArray
object with 256 bytes inside of it.我有一个QByteArray
对象,里面有 256 个字节。 However, when I try to convert it to a byte string ( std::string
), it comes up with a length of 0 to 256. It is very inconsistent with how long the string is, but there are always 256 bytes in the array.但是,当我尝试将其转换为字节字符串( std::string
)时,它的长度为 0 到 256。与std::string
的长度非常不一致,但数组中总是有 256 个字节. This data is encrypted and as such I expect a 256-character garbage output, but instead I am getting a random number of bytes.这些数据是加密的,因此我期望有 256 个字符的垃圾输出,但我得到的是随机数的字节。
Here is the code I used to try to convert it:这是我用来尝试转换它的代码:
// Fills array with 256 bytes (I have tried read(256) and got the same random output)
QByteArray byteRecv = socket->read(2048);
// Gives out random garbage (not the 256-character garbage that I need)
string recv = byteRecv.constData();
The socket
object is a QTcpSocket*
if it's necessary to know.如果有必要知道, socket
对象是QTcpSocket*
。
Is there any way I can get an exact representation of what's in the array?有什么方法可以准确表示数组中的内容吗? I have tried converting it to a QString
and using the QByteArray::toStdString()
method, but neither of those worked to solve the problem.我尝试将其转换为QString
并使用QByteArray::toStdString()
方法,但这些方法都无法解决问题。
QByteArray::constData()
member function returns a raw pointer const char*
. QByteArray::constData()
成员函数返回一个原始指针const char*
。 The constructor of std::string
from a raw pointer来自原始指针的std::string
构造函数
std::string(const char* s);
constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s
.使用s
指向的以空字符结尾的字符串的副本初始化内容来构造字符串。 The length of the string is determined by the first null character.字符串的长度由第一个空字符决定。 If s
does not point to such a string, the behaviour is undefined.如果s
不指向这样的字符串,则行为未定义。
Your buffer is not a null-terminated string and can contain null characters in the middle.您的缓冲区不是以空字符结尾的字符串,中间可以包含空字符。 So you should use another constructor所以你应该使用另一个构造函数
std::string(const char* s, std::size_type count);
that constructs the string with the first count
characters of character string pointed to by s
.用s
指向的字符串的前count
字符构造字符串。
That is:那是:
std::string recv(byteRecv.constData(), 256);
For a collection of raw bytes, std::vector
might be a better choice.对于原始字节的集合, std::vector
可能是更好的选择。 You can construct it from two pointers:您可以从两个指针构造它:
std::vector<char> recv(byteRecv.constData(), byteRecv.constData() + 256);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.