Java是否有一种方法可以将int转换为ASCII符号?
你想将 int
转换为 char
吗?
int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
// Output:
// 33
// !
或者您想将 int
转换为 String
?
int yourInt = 33;
String str = String.valueOf(yourInt);
或者你指的是什么?
int iAsciiValue = 9; // Currently just the number 9, but we want Tab character
// Put the tab character into a string
String strAsciiTab = Character.toString((char) iAsciiValue);
有许多方法可以将int转换为ASCII(取决于您的需求),但是这里是一种将每个整数字节转换为ASCII字符的方法:
private static String toASCII(int value) {
int length = 4;
StringBuilder builder = new StringBuilder(length);
for (int i = length - 1; i >= 0; i--) {
builder.append((char) ((value >> (8 * i)) & 0xFF));
}
return builder.toString();
}
byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };
int value = ByteBuffer.wrap(test).getInt(); // 1413829460
System.out.println(toASCII(value)); // outputs "TEST"
这实际上将32位整数中的4个字节转换为4个单独的ASCII字符(每个字节一个字符)。
char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));
输出:
Character: 1
Character: 49
使用Character#toString
而不是char
。
String result = Character.toString( yourAsciiNumber ) ;
例:
Character.toString( 97 ) // LATIN SMALL LETTER A
a
Character.toString( 128_567 ) // FACE WITH MEDICAL MASK
char
是遗留的在Java中,char
类型是遗留的,并且基本上是有问题的。作为一个16位值,char
无法表示由Unicode定义的大多数字符。
这个成功了:
System.out.println( Character.toString( 128_567 )); // Unicode code points handle full-range of Unicode characters.
这个失败了:
System.out.println( ( char ) 128_567 ); // `char` fails with most Unicode characters.
请查看 IdeOne.com 上的代码运行实例。
使用代码点整数数字来表示单个字母。
US-ASCII是Unicode的子集。因此,任何US-ASCII数字(0-127)也是Unicode代码点(0-1,114,111)。
要将代码点数字更改为包含单个字符的String
对象,请调用{{link4:Character#toString
}}。
String x = Character.toString( 97 ) ;
a
在Java中,您真的想使用Integer.toString将整数转换为相应的字符串值。如果您只处理数字0-9,则可以使用以下内容:
private static final char[] DIGITS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
private static char getDigit(int digitValue) {
assertInRange(digitValue, 0, 9);
return DIGITS[digitValue];
}
private static int ASCII_ZERO = 0x30;
private static char getDigit(int digitValue) {
assertInRange(digitValue, 0, 9);
return ((char) (digitValue + ASCII_ZERO));
}
最简单的方法是使用类型转换:
public char toChar(int c) {
return (char)c;
}
int num = 33;
System.out.println((char) num); //Outputs 33
//if you want to find the integer value of character instead.
//Just do the reverse
char ch = '%';
System.out.println((int) ch);