10

Possible Duplicate:
C++ convert hex string to signed integer

I allready searched on google but didn't find any help. So heres my problem: I have strings that allready contains hex code e.g.: string s1 = "5f0066" and i want to convert this string to hex. I need to compare the string with hex code i've read in a binary file.

(Just need the basic idea how to convert the string) 5f Best regards and thanks.

Edit: Got the binary file info in the format of unsigned char. SO its 0x5f... WOuld like to have teh string in the same format

Community
  • 1
  • 1
Homer
  • 113
  • 1
  • 2
  • 6
  • 2
    What does mean "want to convert this string to hex" if they already are in hex? – Alessandro Pezzato Jul 23 '12 at 08:30
  • `strtol()` from ``? Just guessing, your question is not very clear. – DevSolar Jul 23 '12 at 08:31
  • In case you read these strings from file (specifically, from `std::ifstream`), [this](http://stackoverflow.com/questions/5555849/reading-hex-values-from-fstream-into-int) may be a better answer than the duplicate question posted above. – jogojapan Jul 23 '12 at 08:33

3 Answers3

19

Use std:stoi as (in C++11 only):

std::string s = "5f0066";
int num = std::stoi(s, 0, 16);

Online demo

congusbongus
  • 13,359
  • 7
  • 71
  • 99
Nawaz
  • 353,942
  • 115
  • 666
  • 851
14

Use stringstream and std::hex

std::stringstream str;
std::string s1 = "5f0066";
str << s1;
int value;
str >> std::hex >> value;
Community
  • 1
  • 1
Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185
  • I got the folowing: 1500-030: (I) INFORMATION: std::num_get > >::_Getffld(char *, istreambuf_iterator > &, istreambuf_iterator > &, const locale &): Additional optimization may be attained by recompiling and specifying MAXMEM option with a value greater than 8192. – Vincent Guyard Mar 01 '18 at 21:08
7

strtol(str, NULL, 16) or strtoul(str, NULL, 16) should do what you need.

strtol strtoul

CygnusX1
  • 20,968
  • 5
  • 65
  • 109