在 java 中将字符转换为 ASCII 数值
我有
,然后我做String name = "admin";
String charValue = name.substring(0,1); //charValue="a"
我想将 转换为其ASCII值(97),如何在java中执行此操作?charValue
我有
,然后我做String name = "admin";
String charValue = name.substring(0,1); //charValue="a"
我想将 转换为其ASCII值(97),如何在java中执行此操作?charValue
非常简单。只需将你作为.char
int
char character = 'a';
int ascii = (int) character;
在你的例子中,你需要先从字符串中获取特定的字符,然后强制转换它。
char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.
虽然强制转换不是明确要求的,但它提高了可读性。
int ascii = character; // Even this will do the trick.
只是一种不同的方法
String s = "admin";
byte[] bytes = s.getBytes("US-ASCII");
bytes[0]
将表示 a.的 ascii。以及整个数组中的其他字符。