在软硬件结合的项目中,我们常常需要进行float、double与16进制数之间的转化
转换方法如下:
//float转16进制字符串
float f = 20.321;
uint f_uint = (uint)&f;
QString f_hex = QString("%1").arg(f_uint, 4, 16, QLatin1Char(‘0’)); // 4是生成字符串的最小长度,可以改为8
qDebug() << f_hex; // “41a29168”
//16进制字符串转float
/QString hex_float = “41a29168”;
uint hex_uint = hex_float.toUInt(nullptr, 16);
float hex_res = (float)&hex_uint;
qDebug() << hex_res; // 20.321
//double转16进制字符串
double d = 20.321;
qulonglong d_long = (qulonglong)&d;
QString d_hex = QString("%1").arg(d_long, 8, 16, QLatin1Char(‘0’));
qDebug() << d_hex; // “4034522d0e560419”
//16进制字符串转double
QString hex_double = “4034522d0e560419”;
qulonglong hex_long = hex_double.toULongLong(nullptr, 16);
double hex_d = (double)&hex_long;
qDebug() << hex_d; // 20.321