Search code examples
c++winapireadprocessmemory

C++/CPP Reading an added hex address


I'm still relatively new-ish to CPP but I can't find any source that has my issue. My IDE is MSVC 2017 Preview and my desired outcome is to add two hex addresses together, then read the address' value. I'm not sure why but it's not playing nicely with adding hex numbers. I'll give you my current example:

int number;
ReadProcessMemory(pHandle, (void*)(0x37c90000 + 0xE29FE8), &number, sizeof(number), 0);
std::cout << number << " for " << std::hex << (0x37c90000 + 0xE29FE8) << std::endl;

ReadProcessMemory(pHandle, (void*)(0x38ab9fe8), &number, sizeof(number), 0);
std::cout << number << " for " << std::hex << (0x38ab9fe8) << std::endl;

std::cout << "a = " << (0x37c90000 + 0xE29FE8) << std::endl;
std::cout << "b = " << (0x38ab9fe8) << std::endl;

My predicted outcome of this code would be that both ReadProcessMemory should get the same exact same value, but instead only the second ReadProcessMemory (with the already added hex value) returns properly.

Furthermore, cout-ing A and B report the exact same address. If that's the case, why is ReadProcessMemory throwing a tantrum and reporting a negative number on the first ReadProcessMemory?

Here's my outcome with the code above:

-331287296 for 38ab9fe8
ec40f500 for 38ab9fe8
a = 38ab9fe8
b = 38ab9fe8

Apologies but I truly can't figure out why they're different in any way.


Solution

  • No that seems about right. 0xec40f500 is the unsigned hexadecimal representation of the decimal signed value -331287296. Please learn about two's complement representation of negative numbers.

    The problem is, I believe, the std::hex manipulator, which is sticky. If you in the second case use std::dec both numbers will be displayed as decimal:

    // Second output
    std::cout << std::dec << number << " for " << std::hex << (0x38ab9fe8) << std::endl;
    //           ^^^^^^^^
    // Display *all* following numbers as decimal
    

    Or use std::hex in the first output:

    // First output
    std::cout << std::hex << number << " for " << (0x37c90000 + 0xE29FE8) << std::endl;
    //           ^^^^^^^^
    // Display *all* following numbers as hexadecimal
    

    Of course, if you intend for number to be unsigned, you need to explicitly say so when defining the variable. Perhaps it would be easier for you to see the connection between 0xec40f500 and the unsigned decimal value 3963680000?