Realise that a char is just a small integer. Have a look at an ASCII table to see what the first 10 chars are. This will lead to the wisdom of salem c answer :+)
@chipp, you are passing a char into the function, so even 0 - 9 is a char in the function. Simply casting a char to an int doesn't covert to an int. (HINT: ASCII table as TheIdeasMan mentioned) http://www.cplusplus.com/doc/ascii/
1 2 3 4 5 6 7 8 9
#include <iostream>
int main()
{
for (char i { '0' }; i <= '9'; ++i)
{
std::cout << '\'' << i << '\'' << " = " << (int) i << '\n';
}
}
#include <string>
#include <iostream>
int hex_conv_check(char param)
{
if (param >= 'A' && param <= 'F')
return param - 'A' + 10;
if (param >= 'a' && param <= 'f')
return param - 'a' + 10;
if (param >= '0' && param <= '9')
return param - '0';
std::cout << "Wrong input!\n";
return -1;
}
int hex_conv(const std::string& base) {
int res {};
for (constauto& d : base)
res = res * 16 + hex_conv_check(d);
return res;
}
int main()
{
std::cout << hex_conv("12FE6") << '\n';
}
The issue, of course, is signal that a char is not a valid hex.
This is done in hex_conv as well as the conversion. This method means that somehow an invalid char has also to have a return value (as a function with a return type has to return a value of that type). Here it's -1.
It will - as you're casting param to an int - which is duly reported as an int by typeid!
Note that char is a signed (usually) 8 bit number. digits, letters etc are represented by their ASCII values with '0' being 48 etc. Don't confuse 0 (the number 0) with '0' which is the char 'a' with a value of 48. '0' and 48 can be interchanged. Same with the other ASCII chars.
so you guys mean that if param contain number 0, it will be as the type of char (as it is the original type) which have integer value 48 and thus it's converted to int as 48 in this code??
so you guys mean that if param contain number 0, it will be as the type of char (as it is the original type) which have integer value 48 and thus it's converted to int as 48 in this code??
so you guys mean that if param contain number 0, it will be as the type of char (as it is the original type) which have integer value 48 and thus it's converted to int as 48 in this code??
Not sure if you understand fully yet: there is no need for casting. '0' is a small integer and will work in comparisons and math operations, as in seeplus code earlier.