If you have a char that is in the range \'0\' to \'9\' how do you convert it to int values of 0 to 9
And then how do you convert it back?
Also given letters
If you know a character c
is either a letter or number, you can just do:
int cton( char c )
{
if( 'a' <= c ) return c-'a';
if( 'A' <= c ) return c-'A';
return c-'0';
}
Add whatever error checking on c
is needed.
To convert an integer n
back to a char
, just do '0'+n
if you want a digit, 'A'+n
if you want an uppercase letter, and 'a'+n
if you want lowercase.
Note: This works for ASCII (as the OP is tagged.) See Pete's informative comment however.