Last active
December 10, 2024 00:25
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.