I have a QByteArray
object with 256 bytes inside of it. 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. This data is encrypted and as such I expect a 256-character garbage output, but instead I am getting a random number of bytes.
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.
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.
QByteArray::constData()
member function returns a raw pointer const char*
. The constructor of std::string
from a raw pointer
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
. 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.
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
.
That is:
std::string recv(byteRecv.constData(), 256);
For a collection of raw bytes, std::vector
might be a better choice. You can construct it from two pointers:
std::vector<char> recv(byteRecv.constData(), byteRecv.constData() + 256);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.