0

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)?

Dada
  • 6,313
  • 7
  • 24
  • 43
Lipa
  • 35
  • 2
  • 10
  • Do you have the values in an array? You can memcpy them into the float, but don't forget the endianess: https://ideone.com/AKUkSE – mch Jan 27 '21 at 13:31
  • yeah @CppProgrammer23 is right. Your question is a bit unclear. Do you want to reinterpret 4byte of memory to be a float? Are your hex values stings? – Robert Andreas Fritsch Jan 27 '21 at 13:32

3 Answers3

2
#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

StPiere
  • 4,113
  • 15
  • 24
1

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

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
-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;
}
kiatng
  • 2,847
  • 32
  • 39
Louise
  • 1