2

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.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
Dororo
  • 3,420
  • 2
  • 30
  • 46

4 Answers4

5

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.

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
markus
  • 495
  • 4
  • 5
  • +1, but why should it break when `sizeof(unsigned int)!=sizeof(float)`? We are telling to `ReadProcessMemory` to read exactly the size of a `float`, if the data read from the other process starts as a `float` (otherwise the whole thing wouldn't make sense :) ) it shouldn't break. – Matteo Italia Feb 20 '11 at 14:16
  • I don't think there is a sizeof problem on platforms where ReadProcessMemory actually exists. This code is not very portable, is it? :-) – Bo Persson Feb 20 '11 at 14:33
4
UINT d= 0x432D4E94;
float f= *(float*)&d; // 173.30695
Sergei Tachenov
  • 24,345
  • 8
  • 57
  • 73
Lior Kogan
  • 19,919
  • 6
  • 53
  • 85
4

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.

6502
  • 112,025
  • 15
  • 165
  • 265
2
unsigned int input = 1127042708;

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

or

float output = *(float*)(&input)
Fox32
  • 13,126
  • 9
  • 50
  • 71