在java中将字符转换为ASCII数值
问题描述:
我有 String name = "admin";
然后我做 String charValue = name.substring(0,1);//charValue="a"
我想将 charValue
转换为它的 ASCII 值 (97),我该如何在 java 中做到这一点?
I want to convert the charValue
to its ASCII value (97), how can I do this in java?
答
很简单.只需将您的 char
转换为 int
.
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.