首页 > 解决方案 > 如何将 0x 填充添加到变量中的 uintptr_t?

问题描述

所以我想弄清楚如何将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没有填充。

标签: c++hexcout

解决方案


两种情况下打印的表达式类型都是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

推荐阅读