从float转换为QByteArray [英] Convert from float to QByteArray
问题描述
有一种快速方法可以在 QByteArray
?中将浮点值转换为字节形式(十六进制)表示
在使用数组之前,使用 memcpy()
做过类似的操作,但这并不适用于 QByteArray
。
例如:
memcpy(& byteArrayData ,& floatData,sizeof(float));
可以使用其他方式使用:
float * value =(float *)byteArrayData.data();
我只是实现这个错误或者有更好的方法来使用Qt? >
感谢
从 QByteArray类参考页面:
float f = 0.0f;
QByteArray数组(reinterpret_cast< const char *>(& f),sizeof(f));
将使用内存内容初始化 QByteArray
如果您已经有一个,并且只想将数据附加到它:
array.append(reinterpret_cast< const char *>(& f),sizeof(f));
也应该这样做。
要反过来,你只需要执行相反的操作:
float f2;
if(array.size()> = sizeof(f2)
{
f2 = * reinterpret_cast< const float *>(array.data());
} else
{
//数组不够大
}
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
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.
}
这篇关于从float转换为QByteArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!