3

I have searched online, but it doesn't seem to be a solution to my problem. Basically I have a std::string which contains a hexadecimal memory address (like 0x10FD7F04, for example). This number is read from a text file and saved as a std::string, obviously.

I need to convert this string to an int value, but keeping the hex notation, 0x. Is there any way to do this?

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
jndok
  • 909
  • 3
  • 14
  • 28

3 Answers3

5

You can use C++11 std::stoi function:

#include <iostream>
#include <iomanip>
#include <string>

int main()
{
    std::string your_string_rep{"0x10FD7F04"};
    int int_rep = stoi(your_string_rep, 0, 16);
    std::cout << int_rep << '\n';
    std::cout << std::hex << std::showbase << int_rep << '\n';
}

Outputs:

285048580
0x10fd7f04
Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
4

I need to convert this string to an int value, but keeping the hex notation, 0x. Is there any way to do this?

There are two parts to your question:

  1. Convert the string hexadecimal representation to an integer.

    std::string your_string_rep{ "0x10FD7F04" };
    std::istringstream buffer{ your_string_rep };
    int value = 0;
    buffer >> std::hex >> value;
    
  2. Keeping the hex notation on the resulting value. This is not necessary/possible, because an int is already a hexadecimal value (and a decimal value and a binary value, depending on how you interpret it).

In other words, with the code above, you can just write:

    assert(value == 0x10FD7F04); // will evaluate to true (assertion passes)
Mogsdad
  • 44,709
  • 21
  • 151
  • 275
utnapistim
  • 26,809
  • 3
  • 46
  • 82
1

Alternatively you can use something like this

std::string hexstring("0x10FD7F04");
int num;
sscanf( hexstring.data(), "%x", &num);
Sankar
  • 41
  • 1
  • 4