Valhalla Legends Archive

Programming => General Programming => Java Programming => Topic started by: touchstone on January 25, 2004, 10:52 AM

Title: char to integer conversion
Post by: touchstone on January 25, 2004, 10:52 AM
hi, i need to convert char to int.

say i have  char  c ='3' ;

            i want to get  integer 3 from it ......how can i get it??? how can i convert??

i canot use parseInt() here bocoz "c"  is not a string.....what is the way to get an  int from a char like above example????
Title: Re:char to integer conversion
Post by: Kp on January 25, 2004, 11:03 AM
char c = '3';
int i = c - '0';

/* done */
Title: Re:char to integer conversion
Post by: iago on January 25, 2004, 11:18 AM
You might want to do sanity checking on c, though, to make sure that it's >='0' and <= '9'.  If it's over a certain character, it'll end up as a negative integer which will blow stuff up.
Title: Re:char to integer conversion
Post by: touchstone on January 25, 2004, 02:58 PM
thanks kp.....its ok now.

To iago
---------

".... You might want to do sanity checking on c, though, to make sure that it's >='0' and <= '9'.  If it's over a certain character, it'll end up as a negative integer which will blow stuff up.... "

i could not get you.... could you  plz give an example what you wanted to mean???
Title: Re:char to integer conversion
Post by: K on January 25, 2004, 03:09 PM
I'm not sure of the java syntax, but probably something like:


int CharToInt(char c) throws SomeException
{
    if (c < '0' || c > '9')
         throw new ArgumentOutOfRangeException();

     return c - '0';
}