• Welcome to Valhalla Legends Archive.
 

char to integer conversion

Started by touchstone, January 25, 2004, 10:52 AM

Previous topic - Next topic

touchstone

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????

Kp

char c = '3';
int i = c - '0';

/* done */
[19:20:23] (BotNet) <[vL]Kp> Any idiot can make a bot with CSB, and many do!

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.
This'll make an interesting test for broken AV:
QuoteX5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*


touchstone

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???

K

#4
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';
}