Jedyny zgody ze standardem sposób to:
#include <cstdint>
#include <cstring>
#include <iostream>
uint32_t float2uin32(float data) {
uint32_t ret = 0;
std::memcpy(&ret, &data, sizeof(float));
return ret;
}
int main() {
float f{8};
uint32_t f_uint = float2uin32(f);
std::cout << "float=" << f << " uint32_t=" << f_uint << " hex:0x"
<< std::hex << f_uint;
}
Raczyłbym się nie zgodzić: std::hexfloat
https://godbolt.org/z/TrGW5fzaE
#include <iostream>
#include <iomanip>
#include <string_view>
#include <cmath>
using namespace std::literals;
std::string_view show_classification(double x) {
switch(std::fpclassify(x)) {
case FP_INFINITE: return "Inf"sv;
case FP_NAN: return "NaN"sv;
case FP_NORMAL: return "normal"sv;
case FP_SUBNORMAL: return "subnormal"sv;
case FP_ZERO: return "zero"sv;
default: return "unknown"sv;
}
}
int main()
{
double x;
while (std::cin >> x) {
std::cout
<< std::defaultfloat << std::setw(10) << std::right << x
<< " "
<< std::hexfloat << std::left << std::setw(24) << x
<< show_classification(x)
<< '\n';
}
return 0;
}
Rozwiązanie od hauleth
z memcpy jedynie ukrywa fakt, że standard C++ nie definiuje jaka jest reprezentacja liczb zmiennoprzecinkowych, ergo ten sam kod może dać zupełnie inny wynik na różnych platformach.