Reputation: 13
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?
Upvotes: 1
Views: 332
Reputation:
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.
Upvotes: 0
Reputation: 182829
You're writing text to Actual
.
Hex 30
is the ASCII code for a zero digit.
Upvotes: 3