#include
#include
std::string float_to_string(float fl)
{
std::vector a(sizeof(float));
memcpy(&a[0], &fl, sizeof(float));
std::string result;
for (unsigned char byte : a) {
char hex[3];
snprintf(hex, sizeof(hex), "x", byte);
result = hex;
}
return result;
}
std::string float_to_string(double dl)
{
std::vector a(sizeof(double));
memcpy(&a[0], &dl, sizeof(double));
std::string result;
for (unsigned char byte : a) {
char hex[3];
snprintf(hex, sizeof(hex), "x", byte);
result = hex;
}
return result;
}
float string_to_float(std::string f1)
{
std::vector a(4);
for (int i = 0; i < 4; i) {
a = std::stoul(f1.substr(i * 2, 2), nullptr, 16);
}
float fl;
memcpy(&fl, &a[0], sizeof(float));
return fl;
}
double string_to_double(std::string d1)
{
std::vector a(8);
for (int i = 0; i < 8; i) {
a = std::stoul(d1.substr(i * 2, 2), nullptr, 16);
}
double dl;
memcpy(&dl, &a[0], sizeof(double));
return dl;
}
int main()
{
// 测试转换函数
float f = 3.14f;
double d = 6.28;
std::string floathex = float_to_string(f);
std::string doublehex = float_to_string(d);
std::cout << "float to hex string: " << floathex << std::endl;
std::cout << "double to hex string: " << doublehex << std::endl;
float convertedfloat = string_to_float(floathex);
double converteddouble = string_to_double(doublehex);
std::cout << "hex string to float: " << convertedfloat << std::endl;
std::cout << "hex string to double: " << converteddouble << std::endl;
return 0;
}