tags:

views:

137

answers:

2

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

+4  A: 

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.
}
ereOn
You rock, very fast, very detailed answer! It works great, thank you.
radix07
+1  A: 

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();
iconiK
Using a C-style cast is *not* a good idea.
ereOn
@ereOn, it is debatable. In this example it doesn't matter, I used it in order not to type the long reinterpret cast.
iconiK
And what if `f` was const ? You'd have just wiped out the constness while `reinterpret_cast<>` would have generated a compile-time error. Being lazy with the keystrokes **never** pays.
ereOn
Once again, it doesn't matter in an example. I except any self-respecting C++ programmer to know the implications of the different cast operators. But since you insist... changed to reinterpret cast to a const char *.
iconiK
I'm sorry if you somehow felt offended: wasn't meant. We can't assume that the OP knows the difference between C and C++ styles cast. He might just copy-paste what is a simple example to production code, and encounter unexpected issues later on. You answer was obviously correct, but now it is correct **and** shows good practices ! ;) Thanks for editing.
ereOn
@ereOn, nah, wasn't offended at all; you are correct, albeit a bit pointless in this case, but anyway, answer is edited now; move along.
iconiK