C++ 将 4 个十六进制值转换为浮点数

C++ Convert 4 Hex Values to Float

我正在尝试将 4 个十六进制值转换为浮点数。

十六进制值例如 3F A0 00 00。在二进制表示中,它们将对应于 00111111 10100000 00000000 00000000。如果这 4 个二进制值被解释为一个 32 位浮点数(根据 IEEE754),浮点数的十进制值应该是 1,25.

如何在 C++ 中自动将十六进制值转换为十进制浮点数(我使用 Qt 作为框架)?

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    unsigned char bytes[] = {0x3F, 0xA0, 0x00, 0x00};
    
    uint32_t x = bytes[0];
    for (int i = 1; i < std::size(bytes); ++i) x = (x << 8) | bytes[i];

    static_assert(sizeof(float) == sizeof(uint32_t), "Float and uint32_t size dont match. Check another int type");
    
    float f{};
    memcpy(&f, &x, sizeof(x));
    // or since C++20 if available: float f = std::bit_cast<float>(x)
    
    cout << "f = " << f << endl;
}

Live

如果您的实现使用 24 位 IEEE 754 浮点数,则您在该数组中存储了两个可能的值(5.74855e-411.25)- 因此您肯定需要处理字节顺序。

示例:

#include <algorithm>
#include <bit>
#include <cstring>
#include <iostream>
#include <iterator>
#include <limits>

int main() {
    static_assert(std::numeric_limits<float>::is_iec559 &&
                  std::numeric_limits<float>::digits == 24,
                  "Only 24 digit IEEE 754 floats supported");

    unsigned char src[] = {0x3F, 0xA0, 0x00, 0x00};
    float dest;

    if constexpr (std::endian::native == std::endian::little) {
        // swap the byte order
        std::reverse(std::begin(src), std::end(src));
    }

    std::memcpy(&dest, src, sizeof(float));
    
    std::cout << dest << '\n';    // prints 1.25
}

Demo

float Uint32ToFloat(uint32_t data)
{
    float returnData = 0.0;

    static_assert(sizeof(float) == sizeof(uint32_t), "Float and uint32_t size dont match. Check another int type");
    memcpy(&returnData, &data, sizeof(data));
    return returnData;
}