How do I convert an std::stringstream to a uintptr_t and maintain the hex value?


New Member
Currently, I am attempting to calculate offsets from a pointer address, and the number of offsets to be calculated can change, so the approach must be done dynamically.

I start by looping for the number of offsets I am trying to calculate, each offset is 4 bytes apart, thus I multiply the current iteration by 4, and then attempt to convert the resulting value to a hex address, and store it back in the uintptr_t as a hex value.

This value, in theory, should be the offset I am looking for.

In reality, that is not the case, the value seems to be getting converted back to an integer and stored in the uintptr_t variable.

Expected Output:
Actual Output
for (int i = 1; i < totalEntities + 1; i++)
    // Define a stringstream to store the hex value.
    std::stringstream ss;

    // Define a value that will be converted to hex.
    uintptr_t valueToHex = i * 4;

    // Convert valueToHex to Hex, and store the result in stringstream ss.
    ss << std::hex << valueToHex;

    // Convert stringstream ss to a uintptr_t stored in valueToHex
    ss >> valueToHex;

    // Output result
    std::cout << valueToHex << std::endl;


Thành viên BQT
uintptr_t represents a value of an integer. It does not represent textual representation of that value. The base of the number is not part of the value. 0xC, 12, 014 are indistinguishable values regardless of their different representation.

The base is part of the textual representation. All information besides the value (i.e. all representational details) is lost when an integer is extracted from a character stream.

You can either:

a) Extract a string instead, and insert the extracted string into the output stream. Strings retain most of the textual representation (an exception being that system specific new-line character sequences are converted to \n) or

b) Use std::hex to insert the integer into the output stream in the representation that you want.

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.