簡體   English   中英

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;
}

居住

如果您的實現使用 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
}

演示

浮動 Uint32ToFloat(uint32_t 數據) { 浮動 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;

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM