Page 1 of 1

Char 2 Int

Posted: Fri Aug 19, 2005 11:00 pm
by stafe
Hello,

can anyone tell me how to convert a Charakter to an Integer ??
Mabey somebody has a C function for it ...

Re: Char 2 Int

Posted: Fri Aug 19, 2005 11:00 pm
by blackcatcoder
substract 48 from the char and you have the int value !
(48 = 0 in ASCII) !

like this

int char_to_int(char c)
{
if (c>=48 && c<=57) // if you only want to convert values!
{ return (c-48);
}else{return -1;}
}

Re: Char 2 Int

Posted: Fri Aug 19, 2005 11:00 pm
by carbonBased
char c;
int i = (int)c

:)

Re: Char 2 Int

Posted: Sat Aug 20, 2005 11:00 pm
by blackcatcoder
carbonBased

yours is also correct but you only get the int value of the ascii code ! ;-)

Re: Char 2 Int

Posted: Tue Aug 23, 2005 11:00 pm
by carbonBased
I realize that. My point was simply that, from the question, it can be interpreted more then one way.

--Jeff

Re: Char 2 Int

Posted: Mon Aug 29, 2005 11:00 pm
by blackcatcoder
jep

Re: Char 2 Int

Posted: Mon Aug 29, 2005 11:00 pm
by Phibred
Let c = the char.

Code: Select all

int number = c - ((int)'0');

Yes blackcatcoder, this exactly what you wrote, but there is no point doing any 'allowence' checking, and for god sakes just use '0' instead of what ever it happens to be, much easier to read. :P

And for people like me who want this in ASM....

Code: Select all

;eax = char -> int after calc
CharToInt:
sub eax, '0' ; wow that was easy.
ret

Re: Char 2 Int

Posted: Wed Aug 31, 2005 11:00 pm
by proxy
this reminds me of one of my favorite sarcastic C help sites:

http://www.plethora.net/~seebs/faqs/c-i ... #section-7

that should address this question quite nicely

proxy

Re: Char 2 Int

Posted: Thu Sep 01, 2005 11:00 pm
by blackcatcoder
Phibred yours is really nice but it's recommend to know that int ('0') is 48 in ASCII ! ;-)

I've only prevented to convert numbers to an int, and not any other character like an 'B' or something else!