Convert from float to QByteArray

Is there a quick way to convert a float value to a byte (hexadecimal) representation in a QByteArray ?

They did an analogy with memcpy() before using arrays, but this does not seem to work with QByteArray .

For instance:

 memcpy(&byteArrayData,&floatData,sizeof(float)); 

You can use another method perfectly:

 float *value= (float *)byteArrayData.data(); 

Am I just implementing this incorrectly or is there a better way to do this with Qt?

thanks

+4
source share
2 answers

From the QByteArray class description :

 float f = 0.0f; QByteArray array(reinterpret_cast<const char*>(&f), sizeof(f)); 

A QByteArray will be initialized with the contents of the memory of the float stored in it.

If you already have and just want to add data to it:

 array.append(reinterpret_cast<const char*>(&f), sizeof(f)); 

Must do it.

To go the other way around, you just need to do the reverse operation:

 float f2; if (array.size() >= sizeof(f2) { f2 = *reinterpret_cast<const float*>(array.data()); } else { // The array is not big enough. } 
+17
source

I'm not sure what you want for sure.

To write a binary representation in a QByteArray, you can use this:

 float f = 0.0f; QByteArray ba(reinterpret_cast<const char *>(&f), sizeof (f)); 

To get the hexadecimal representation of a float, you can add this:

 QByteArray baHex = ba.toHex(); 
+3
source

Source: https://habr.com/ru/post/1308889/


All Articles