4

I am trying to copy the value in bar into the integer foo.

This is what I have so far. When I run it I get a different hex value. Any help would be great.

int main()
{

    string bar = "0x00EB0C62";

    int foo = (int)bar;

    cout << hex << foo;
    ChangeMemVal("pinball.exe", (void*) foo, "100000", 4);

    return 0;
}

So the output should be 0x00EB0C62.

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
  • Exact Duplicate: http://stackoverflow.com/questions/200090/how-do-you-convert-a-c-string-to-an-int – Martin York Feb 03 '09 at 18:03
  • duplicate, as per Matta's comment. pls delete –  Feb 03 '09 at 18:03
  • This one deals with hex numbers which may be informative to those who aren't familiar with different formats for numbers. I'd say leave it. – Ron Warholic Feb 03 '09 at 18:05
  • I'm not trying to convert the hex to decimal I am trying to copy the hex value into the integer foo. –  Feb 03 '09 at 18:14

5 Answers5

2

atoi should work:

string bar = "0x00EB0C62";

int foo = atoi(bar.c_str());
scottm
  • 27,829
  • 22
  • 107
  • 159
2

Previous SO answer.

Community
  • 1
  • 1
alxp
  • 6,153
  • 1
  • 22
  • 19
2

Atoi certainly works, but if you want to do it the C++ way, stringstreams are the way the go. It goes something like this, note, code isn't tested and will probably not work out of the box but you should get the general idea.

int i = 4;
stringstream ss;
ss << i;
string str = ss.str();
1

when you cast a string as an int, you get the ascii value of that string, not the converted string value, to properly convert 0x00EB0C62, you will have to pass it through a string parser. (one easy way is to do ascii arithmetic).

z -
  • 7,130
  • 3
  • 40
  • 68
1

This is what the string streams are for, you want to do something like this.

#include< sstream>
#include< string>
#include< iostream>
int main()
{
    std::string bar="0x00EB0C62";

    int foo=0;

    std::istringstream to_int;
    to_int.str(bar);
    to_int>>foo;

    std::cout<<std::ios_base::hex<<foo<<std::endl;;

    .
    etc.
    .

    return EXIT_SUCCESS;
}

That should do the trick. Sorry if I got the ios_base incorrect I can't remember the exact location of the hex flag without a reference.

James Matta
  • 1,562
  • 16
  • 37