9

I tried to convert QByteArray to std::vector<unsigned char> using this code:

unsigned char* buffer = (unsigned char*)byteArrayBuffer.constData();
std::vector<unsigned char>::size_type size = strlen((const char*)buffer);
std::vector<unsigned char> bufferToCompress(buffer, buffer + size);

but, assuming that byteArrayBuffer is a QByteArray filled with data, I think it doesn't work well on line unsigned char* buffer = (unsigned char*)byteArrayBuffer.constData(); because byteArrayBuffer.size() returns a different value than bufferToCompress.size().

How can I get it working?

Jacob Krieg
  • 2,834
  • 15
  • 68
  • 140

2 Answers2

23

I'm not familiar with Qt, but surely you just want

std::vector<unsigned char> bufferToCompress(
    byteArrayBuffer.begin(), byteArrayBuffer.end());

Note: strlen is not particularly useful in C++; it tells you the length of a C-style null-terminated string (by searching memory until it either finds either finds a zero-valued byte, or falls off the end of accessible memory and crashes), but can't tell you the size of an array, which is what you'd need here. Also, using evil C-style casts to force invalid code to compile is never a good idea.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

As I see here http://qt-project.org/doc/qt-4.8/qbytearray.html QByteArray does not have begin/end methods. But have data/length. Result code may be looks like this:

const unsigned char* begin = reinterpret_cast<unsigned char*>(byteArrayBuffer.data());
const unsigned char* end = begin + byteArrayBuffer.length();
std::vector<unsigned char> bufferToCompress( begin, end );
αλεχολυτ
  • 4,792
  • 1
  • 35
  • 71
  • 7
    It's odd that `begin` and `end` seem to be undocumented; they certainly [exist](https://qt.gitorious.org/qt/qtbase/source/68fb37d762a818cc44ea69f7c3a80a3f010b6713:src/corelib/tools/qbytearray.h#L362). – Mike Seymour Jan 28 '14 at 12:40