开发者

Converting uint to float in C++

开发者 https://www.devze.com 2023-02-12 08:28 出处:网络
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 rep开发者_运维技巧

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 rep开发者_运维技巧resentation 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.


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.


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


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.


unsigned int input = 1127042708;

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

or

float output = *(float*)(&input)
0

精彩评论

暂无评论...
验证码 换一张
取 消