I need a forumla

Sep 21, 2012 at 4:47am
To convert ASCII into a number.
For example, if I had ASCII 50. I need to convert into the number 2.

My prof was saying some thing about sum of crap.. And... well.. idk, I just a formula. ;)
Last edited on Sep 21, 2012 at 4:48am
Sep 21, 2012 at 4:53am
1
2
3
4
5
6
int convertToInt(char c)
{
    if (isdigit(c))
        return c - '0';
    return -1; //c is not a digit
}


http://cplusplus.com/reference/clibrary/cctype/isdigit/

or you can use atoi to convert string to integer
http://cplusplus.com/reference/clibrary/cstdlib/atoi/
Last edited on Sep 21, 2012 at 4:54am
Sep 21, 2012 at 5:11am
Could you explain why a character - '0' would convert it to a int?
Sep 21, 2012 at 5:21am
Also, I don't have to use isdigit() because all the ASCII values I'll be working with will be digits. And I can't use any built in functions.

There's gotta some type of formula for calculating it.
Sep 21, 2012 at 5:26am
you can use
atoi()
function which convert ascii into integer.
Sep 21, 2012 at 5:35am
because every ASCII char is an integer.
'0' is 48; 48 - 48 == 0
'1' is 49; 49 - 48 == 1
'2' is 50; 50 - 48 == 2
...
'9' is 57; 57 - 48 == 9

so if you want to convert an ASCII char into number, just simply minus 48, or '0' if you can't remember 48. The compiler will treat '0' as 48.
Sep 21, 2012 at 5:38am
Tntxtnt's code would work perfectly.
Last edited on Sep 21, 2012 at 5:40am
Topic archived. No new replies allowed.