Home > Net >  How to add 0x padding to a uintptr_t in a variable?
How to add 0x padding to a uintptr_t in a variable?

Time:10-24

So I'm trying to figure out how can I add 0x padding to a uintptr_t. The current value of it is: 400000.

However I would like it to be 0x400000. So currently to achieve this I am adding the 0x padding when I'm printing this out. However how would I go about this so I can store the padded value of uintprt_t?

uintptr_t modBase = GetModuleBaseAddress(pID, "ac_client.exe");
cout << "0x" << hex << modBase <<endl; //Output is 0x400000

The reason for trying to achieve this is that later I would like to find a dynamic base address as shown here:

uintptr_t dynamicBaseAddress = modBase   0x10f4f4;
cout << "DynamicBaseAddress is: " << dynamicBaseAddress << endl; // Again var is missing 0x

And again the result is: 50f4f4 without the padding.

CodePudding user response:

The type of the expression printed in both cases is uintptr_t, so in both cases output stream behaves the same way, i.e. not add the prefix. As an alternative to @RetiredNinja's suggestion in the comments (use std::showbase), you could create a wrapper type with a custom operator<< which would allow you to implement the way the information is printed regardless of the current state of the stream (i.e. changing back to decimal in between wouldn't change, how the value is printed).

This does require you to implement operators for operations you want to be available for this type though:

class UintptrWrapper
{
public:
    UintptrWrapper(uintptr_t value)
        : m_value(value)
    {
    }

    //   operation should work, so we need to implement it
    friend UintptrWrapper operator (UintptrWrapper const& summand1, UintptrWrapper const& summand2)
    {
        return { summand1.m_value   summand2.m_value };
    }

    // custom printing of info
    friend std::ostream& operator<<(std::ostream& s, UintptrWrapper const& value)
    {
        auto oldFlags = s.flags();
        s << "0x" << std::hex << value.m_value;
        s.flags(oldFlags);
        return s;
    }
private:
    uintptr_t m_value;
};
UintptrWrapper modBase = 0x400000;
std::cout << modBase << '\n';

auto dynamicBaseAddress = modBase   0x10f4f4; // result is another UintptrWrapper with the same behaviour when writing to the stream as above
std::cout << "DynamicBaseAddress is: " << dynamicBaseAddress << '\n';

Output:

0x400000
DynamicBaseAddress is: 0x50f4f4
  • Related