【问题标题】:C++ Convert 4 Hex Values to FloatC++ 将 4 个十六进制值转换为浮点数
【发布时间】:2021-05-01 08:15:54
【问题描述】:

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

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

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

【问题讨论】:

  • 你有数组中的值吗?您可以将它们存储到浮点数中,但不要忘记字节序:ideone.com/AKUkSE
  • 是的@CppProgrammer23 是对的。你的问题有点不清楚。您想将 4byte 的内存重新解释为浮点数吗?你的十六进制值有刺痛吗?

标签: c++ hex


【解决方案1】:
#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

【讨论】:

  • 请注意,该程序以大端顺序解释字节。
  • OP 没有说明他们想要以什么顺序解释字节。编辑:哦,他们说他们希望值为 1.25。然后他们似乎确实想要大端。
  • 我认为他是隐式的......他对这些浮点值的二进制表示对应于 BE 顺序中的字节。
  • 稍微好一点的 C++20 替代方案:float f = std::bit_cast&lt;float&gt;(x);
  • 另外,为了避免幻数,我推荐作为循环结束条件:i &lt; std::size(bytes)
【解决方案2】:

如果您的实现使用 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

【讨论】:

    【解决方案3】:
    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;
    }
    

    【讨论】:

    • 我看不出这如何为接受的答案添加任何内容
    • 数据在内存中是 uint32 hex。当您返回一个浮点数时,它由 machine 处理。类似于铸造。
    • 是的,但它为接受的答案增加了什么? StPiere 已经解释过了。
    猜你喜欢
    • 2014-03-01
    • 1970-01-01
    • 2010-12-08
    • 2011-03-05
    • 1970-01-01
    • 2015-12-28
    • 2016-06-02
    • 1970-01-01
    相关资源
    最近更新 更多