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?
In Java, the char variable stores the ASCII value of a character (number between 0 and 127) rather than the character itself. The ASCII value of lowercase alphabets are from 97 to 122. And, the ASCII value of uppercase alphabets are from 65 to 90. That is, alphabet a is stored as 97 and alphabet z is stored as 122.
Convert String to ASCII 2.1 We can use String. getBytes(StandardCharsets. US_ASCII) to convert the string into a byte arrays byte[] , and upcast the byte to int to get the ASCII value. 2.2 Java 9, there is a new API String.
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.
just a different approach
String s = "admin";
byte[] bytes = s.getBytes("US-ASCII");
bytes[0]
will represent ascii of a.. and thus the other characters in the whole array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With