Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ convert string to hex [duplicate]

Tags:

c++

string

hex

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

like image 391
Homer Avatar asked Jul 23 '12 08:07

Homer


People also ask

How to convert a string to hexadecimal in C?

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.

How does stoi work in C++?

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.

How can I convert a hex string to an integer value?

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.

How do I convert a string to an int in C++?

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.


1 Answers

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

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

Online demo

like image 93
Nawaz Avatar answered Sep 18 '22 12:09

Nawaz