Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from float to QByteArray

Tags:

c++

c

qt

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

Have done similar with memcpy() before using arrays, but this doesn't seem to work too well with QByteArray.

For example:

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

Can go the other way just fine using:

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

Am I just implementing this wrong or is there a better way to do it using Qt?

Thanks

like image 348
radix07 Avatar asked May 05 '10 14:05

radix07


2 Answers

From the QByteArray Class Reference page:

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

Will initialize a QByteArray with the memory content of the float stored in it.

If you already have one and just want to append the data to it:

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

Should do it as well.

To go the other way around, you just have to perform the reverse operation:

float f2;

if (array.size() >= sizeof(f2)
{
  f2 = *reinterpret_cast<const float*>(array.data());
} else
{
  // The array is not big enough.
}
like image 105
ereOn Avatar answered Oct 24 '22 05:10

ereOn


I'm not sure what you want exactly.

To stuff the binary representation into a QByteArray you can use this:

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

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

QByteArray baHex = ba.toHex();
like image 40
CMircea Avatar answered Oct 24 '22 05:10

CMircea