Home > Blockchain >  Convert QByteArray to uint8_t*(uint8_t array)
Convert QByteArray to uint8_t*(uint8_t array)

Time:02-01

How can I convert QByteArray coming from QFile::readAll() into a uint8_t array(uint8_t*)?

I tried static_cast<>() but didn't seemed to work for whole array.

examples of what I've done with static_cast:

uint8_t* x = new uint8_t;
x[0] = static_cast<uint8_t>(testWav.readAll()[0]);
uint8_t* x = new uint8_t;
*x = static_cast<uint8_t>(*testWav.readAll());

etc. didn't work

CodePudding user response:

This doesn't do what you want.

 uint8_t* x = new uint8_t;
 x[0] = static_cast<uint8_t>(testWav.readAll()[0]);

This way you copy only [0] element of array. The rest of allocated memory stay uninitialized

This cannot work at all:

uint8_t* x = new uint8_t;
*x = static_cast<uint8_t>(*testWav.readAll());

QByteArray is a class-type of dynamic container, so you can't use static_cast to access its data as an array, it's a principally different, incompatible data structure. And you're still assigning only the first element: *x is an equivalent of x[0].

QByteArray has method QByteArray::data() which returns a pointer to char*: https://doc.qt.io/qt-6/qbytearray.html#data

The pointer returned by data() isn't owning one and points to memory allocated by class, so data contained in QByteArray which returned by readAll() will cease to exist at end of statement containing it, unless it's assigned to a more persistent storage:

QByteArray fileContent = file.readAll();
char *buffer = fileContent.data();

Result of fileContent.size() would give the actual size of buffer. Note that in some cases it's more convenient to work with QByteArray instead of a raw pointer. You need conversion ONLY if you have to use some API taking raw pointer or face some performance issues.

CodePudding user response:

I think first you need to know that a pointer is not an array. And that you cannot assing a c-array as a whole.

Then you should reconsider if you actually need to convert anything. QByteArray grants you access to the underlying array via its data member. (I find it a bit unfortunate that QByteArray is based on char rather than unsigned char, so you'd want to check whether char is signed or not).

Eventually, if you still want, you can write a loop to copy elements from the QByteArray to another array.

  •  Tags:  
  • c qt
  • Related