在java中将字符转换为ASCII数值 [英] Convert character to ASCII numeric value in java

查看:1253
本文介绍了在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.

这篇关于在java中将字符转换为ASCII数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆