Skip to content

Instantly share code, notes, and snippets.

@haseeb-heaven
Last active December 10, 2024 00:25
Show Gist options
  • Save haseeb-heaven/409bdc5f10ad56c7fa59802315976d49 to your computer and use it in GitHub Desktop.
Save haseeb-heaven/409bdc5f10ad56c7fa59802315976d49 to your computer and use it in GitHub Desktop.
A C++17 tool convertes hexadecima into floating-point numbers. It features functions for parsing input, swapping byte order, and converting to float. The code emphasizes clarity, efficiency, and robust error handling to ensure reliable performance. Was actually derived from https://gregstoll.com/~gregstoll/floattohex/
#include <iostream>
#include <iomanip>
#include <string>
#include <stdexcept>
#include <cstdint>
#include <cstring>
#include <limits>
#include <cstdlib>
float parse_hex_to_float(const std::string& hex_str) {
uint32_t value = std::stoul(hex_str, nullptr, 16);
value = ((value & 0x000000FFU) << 24) |
((value & 0x0000FF00U) << 8) |
((value & 0x00FF0000U) >> 8) |
((value & 0xFF000000U) >> 24);
float result;
std::memcpy(&result, &value, sizeof(result));
return result;
}
int main() {
try {
std::string input = "0000E03F";
float float_result = parse_hex_to_float(input);
std::cout << "Output float: "
<< std::fixed
<< std::setprecision(std::numeric_limits<float>::digits10)
<< float_result << "\n";
return EXIT_SUCCESS;
}
catch (const std::exception& exception) {
std::cerr << "Error: " << exception.what() << "\n";
return EXIT_FAILURE;
}
}
@haseeb-heaven
Copy link
Author

haseeb-heaven commented Dec 10, 2024

Original source code in C/C++.
https://gregstoll.com/~gregstoll/floattohex/floattohexmodule.txt

Credits to original author.
Website: https://gregstoll.com/~gregstoll/floattohex/

Optimized by OpenAI Model o1-Mini.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment