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
char c[2]="6A" char *p; int x = atoi(c);//atoi is deprecated int y = strtod(c,&p);//Returns only first digit,rest it considers as string and //returns 0 if first character is non digit char. By using val=strtol(string, NULL, 16); It returns a long type so you might need to check/cast it.
In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings. The stoi() function is relatively new, as it was only added to the language as of its latest revision (C++11) in 2011.
To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.
One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.
Use std:stoi
as (in C++11 only):
std::string s = "5f0066";
int num = std::stoi(s, 0, 16);
Online demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With