Convert character to ASCII numeric value in java

Celta picture Celta · May 9, 2013 · Viewed 940.2k times · Source

I have String name = "admin";
then I do String charValue = name.substring(0,1); //charValue="a"

I want to convert the charValue to its ASCII value (97), how can I do this in java?

Answer

SudoRahul picture SudoRahul · May 9, 2013

Very simple. Just cast your char as an int.

char character = 'a';    
int ascii = (int) character;

In your case, you need to get the specific Character from the String first and then cast it.

char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.

Though cast is not required explicitly, but its improves readability.

int ascii = character; // Even this will do the trick.