从float转换为QByteArray [英] Convert from float to QByteArray

查看:1090
本文介绍了从float转换为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆