Lipa
Lipa

Reputation: 35

C++ Convert 4 Hex Values to Float

I am trying to convert 4 hexadecimal values to a float.

The hex values are for example 3F A0 00 00. In binary representation they would correspond to 00111111 10100000 00000000 00000000. If these 4 binary values are interpreted as one 32-bit float (accordingly to IEEE754) the decimal value of the float should be 1,25.

How to automatically make the conversion from hex values to decimal float in C++ (I am using Qt as Framework)?

Upvotes: 0

Views: 2104

Answers (3)

Louise
Louise

Reputation: 1

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

Upvotes: -1

Ted Lyngmo
Ted Lyngmo

Reputation: 117318

You have two possible values stored in that array (5.74855e-41 and 1.25) if your implementation uses 24 digit IEEE 754 floats - so you definitely need to deal with endianess.

Example:

#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

Upvotes: 1

StPiere
StPiere

Reputation: 4243

#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

Upvotes: 2

Related Questions