如何将 0x 填充添加到变量中的 uintptr_t?

How to add 0x padding to a uintptr_t in a variable?

所以我想弄清楚如何将 0x 填充添加到 uintptr_t。它的当前值为:400000.

不过我希望它是 0x400000。所以目前为了实现这一点,我在打印时添加 0x 填充。但是我该怎么做才能存储 uintprt_t?

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

之所以尝试实现这一点,是因为稍后我想找到一个动态基地址,如下所示:

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

结果又是:50f4f4 没有填充。

两种情况下打印的表达式类型都是uintptr_t,所以两种情况下输出流的行为方式相同,即不添加前缀。作为@RetiredNinja 在评论中的建议的替代方案(使用 std::showbase),您可以创建一个带有自定义 operator<< 的包装器类型,这将允许您实现信息的打印方式,而不管当前状态如何流的(即在两者之间变回十进制不会改变,值是如何打印的)。

这确实需要您为您希望可用于此类型的操作实现运算符:

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';

输出:

0x400000
DynamicBaseAddress is: 0x50f4f4