convert memory address to int

3.6k views Asked by At

I am trying to read memory addresses from an executable running in memory, and then use those memory addresses to walk the PE structure.

I am having trouble because I'm unsure how to convert a 4 byte char array to it's int equivalent.

Here is my code so far:

char buffer[4];
int e_lfanew = 60;

if(!ReadProcessMemory(pHandle, (me32.modBaseAddr + e_lfanew), buffer, 4, NULL))
{
    printf("ReadProcessMemory @ %x Failed (%d)\n", me32.modBaseAddr, GetLastError());
}

The address i'm reading in, in this case 0xE0000000, is the offset of the PE Header. I want to take the memory address I just read and use it as an offset to read from process memory again, but I cannot figure out how to convert it to an int properly.

Any help would be greatly appreciated.

2

There are 2 answers

0
Armen Tsirunyan On
 buffer[0]        | 
(buffer[1] <<  8) |
(buffer[2] << 16) |
(buffer[3] << 24)

or the other way around, depending on whether your high-order byte is buffer[0] or buffer[3]

0
Michael Aaron Safyan On
int MemoryBufferToInt(char* buffer, int buffer_size) {
   int result;
   assert(buffer_size == sizeof(result));
   memcpy(&result, &buffer[0], sizeof(result));
   return result;
} 

The code above assumes that this buffer was obtained from the process, so that the byte order of the memory buffer is the same as the byte order of a regular int on your platform. Otherwise, you can easily contruct the integer for a specific byte order if you know what the byte order of the buffer is.

NOTE that you could just use static_cast<char*>(&result) in place of your buffer as the parameter to the function that retrieves the buffer contents.