方法1:
#include
typedef union Resolve {
float float_data;
unsigned char char_table[4];
} HextoFloat;
HextoFloat HextoFloat_NDI;
int main() {
//char里面只能存''或者16进制,acsii等,不能存string。。。。我好蠢
unsigned char hexByte[4] = {0x3F, 0x7E, 0x3A, 0x79};
for (int i = 0; i < 4; i++) {
HextoFloat_NDI.char_table[i] = hexByte[3 - i];
}
printf("Float = %.20f", HextoFloat_NDI.float_data);
return 0;
}
方法2:
#include
#include
#include
using namespace std;
template T getNum(unsigned char p[]) {
T temp;
memcpy(&temp, p, sizeof(T));
return temp;
}
int main() {
//0x3F7E3A79
//const char *p = "0x793A7E3F";
unsigned char p[4] = {0x79, 0x3A, 0x7E, 0x3F}; //unsigned char 0 ~ 256, char -128 ~ 127, ascii or hex range(0, 256), do not use char.
float _floatPosition;
_floatPosition = getNum(p);
int precision = 20;//精度
cout.precision(precision);
cout << fixed << "保留" << precision << "位小数的hex转float结果为:" << _floatPosition << endl;
return 0;
}