在java中将字符转换为ASCII数值

在java中将字符转换为ASCII数值

问题描述:

我有 String name =admin;

然后我做 String char = name.substring(0, 1); // char =a

我想将 char 转换为ASCII值(97),如何在java中执行此操作?

I want to convert the char 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.