Converting uint to float in C++

13,288

Solution 1

ReadProcessMemory() takes a pointer to void so it is up to you to point it at a float.

float f;
ReadProcessMemory(hProcess, lpBaseAdress, &f, sizeof(f), NULL); 

Note that this will break when sizeof(unsigned int) != sizeof(float).

Casting won't work because it will take the value and not the representation of the integer.

Solution 2

UINT d= 0x432D4E94;
float f= *(float*)&d; // 173.30695

Solution 3

The safest way (that takes in account possible alignment problems) is to use a union

#include <stdio.h>

int main(int argc, const char *argv[])
{
    union FloatOrUInt
    {
        float asFloat;
        unsigned int asUInt;
    } fu;

    fu.asUInt = 1127042708;
    printf("Float value = %0.6f\n", fu.asFloat);

    return 0;
}

Note however that even if you know that floats are in standard IEEE754 format there can be problems for endianness.

Solution 4

unsigned int input = 1127042708;

float output = *reinterpret_cast<float*>(&input)

or

float output = *(float*)(&input)
Share:
13,288
Dororo
Author by

Dororo

Updated on June 04, 2022

Comments

  • Dororo
    Dororo almost 2 years

    I'm using ReadProcessMemory in order to get 4 bytes. The function allows me to represent this as an unsigned int. I wish to represent this as a float; or in other words use the byte representation of this uint for my float. I've tried casting and it does not seem to work.

    Example: byte representation: 94 4E 2D 43

    uint: 1127042708

    float: 173.3069458..

    Any help would be appreciated.