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.

4
  • Exact Duplicate: stackoverflow.com/questions/200090/… Commented Feb 3, 2009 at 18:03
  • duplicate, as per Matta's comment. pls delete Commented Feb 3, 2009 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. Commented Feb 3, 2009 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. Commented Feb 3, 2009 at 18:14

5 Answers 5

2

atoi should work:

string bar = "0x00EB0C62"; int foo = atoi(bar.c_str()); 
Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't work if there are characters such as 'x' is in the string isn't it?
It didn't work for me. It returned 0.
2

Previous SO answer.

Comments

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(); 

Comments

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).

Comments

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.

Comments