1

I'm trying to convert a float value (0.75) to hex and write that converted value to memory.

    char Actual[4];
    float f = 0.75f;
    int i = *(reinterpret_cast<int*>(&f));
    wsprintf(Actual, "%08X", i);
    MessageBox(NULL, Actual, "Float", NULL);

    unsigned long OldProtection;
    VirtualProtect((LPVOID)(0x01234567), 4, PAGE_EXECUTE_READWRITE, &OldProtection);
    memcpy((LPVOID)0x01234567, Actual, 4);
    VirtualProtect((LPVOID)(0x01234567), 4, OldProtection, NULL);

The conversion works quite well and outputs the correct value (3F400000) when using MessageBox.

But when writing the converted value to memory using memcpy the value of the target address is 30303030 and not 3F400000.

I guess I'm missing some additional step. What could be the problem?

1
  • Aside from the floating point issue, writing to a fixed memory address like 0x01234567 seems pretty dangerous to me. Commented Aug 7, 2014 at 6:40

2 Answers 2

3

You're writing text to Actual.

Hex 30 is the ASCII code for a zero digit.

Sign up to request clarification or add additional context in comments.

Comments

0

Why would you want to do that? Is there something special at that address - is it used by some other code (other than that changing it) or you just want to see the "hex value" of the float number by inspecting the process memory at 0x01234567 with external tool? In every case you could just copy the data in the 'f' variable at the desired location.

unsigned long OldProtection;
VirtualProtect((LPVOID) (0x01234567), 4, PAGE_EXECUTE_READWRITE, &OldProtection);
memcpy((LPVOID) 0x01234567, &f, sizeof(float));
VirtualProtect((LPVOID) (0x01234567), 4, OldProtection, NULL);

The 'VirtualProtect' method calls could be mostly unneeded unless you have a special reason for this (commonly data is stored in read/writable locations).

By the way here is some useful information - the 'hex value' you are working with is an architecture specific one and it represents an encoded floating-point number in some bit format which is required by the CPU floating-point arithmetic instructions. In x86 this is IEEE 754.

2 Comments

Thank you very much, &f works. Also you were right, the VirtualProtect was indeed unneeded and thanks for the link!
It may work, but not like you think. Take a look at David Schwartz' answer. That hits the nail. You are overwriting f by writing "3F400000" (IOW, 18 bytes in total) to a buffer that is only 4 bytes in size. You have a buffer overrun.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.