Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

java - 在Java中将字符转换为ASCII数值(Convert character to ASCII numeric value in java)

I have String name = "admin";

(我有String name = "admin";)
then I do String char = name.substring(0,1); //char="a"

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

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

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

  ask by Celta translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Very simple.

(很简单。)

Just cast your char as an int .

(只需将您的charint 。)

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.

(在您的情况下,您需要首先从String中获取特定的Character,然后进行转换。)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...