Java-将int更改为ascii

Java-将int更改为ascii,java,int,Java,Int,java有没有办法将int转换为ascii符号?是否要将ints转换为chars?: int yourInt = 33; char ch = (char) yourInt; System.out.println(yourInt); System.out.println(ch); // Output: // 33 // ! 还是要将ints转换为Strings int yourInt = 33; String str = String.valueOf(yourInt); 或者您的意思是什么?如

java有没有办法将int转换为ascii符号?

是否要将
int
s转换为
char
s?:

int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
// Output:
// 33
// !
还是要将
int
s转换为
String
s

int yourInt = 33;
String str = String.valueOf(yourInt);

或者您的意思是什么?

如果您首先将int转换为char,您将获得ascii代码

例如:

    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);
事实上,在最后的答案中 字符串strAsciiTab=Character.toString((char)iascivalue); 基本部分是(char)iascivalue,它正在执行任务(Character.toString无用)

意思是第一个答案实际上是正确的 char ch=(char)yourInt


如果在您的int=49(或0x31)中,ch将是“1”

有许多方法可以将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();
}
例如,“测试”的ASCII文本可以表示为字节数组:

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字符(每个字节一个字符)。

在Java中,您确实希望使用它将整数转换为相应的字符串值。如果您只处理数字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));
}

您可以在java中将数字转换为ASCII。将数字1(基数为10)转换为ASCII的示例

char k = Character.forDigit(1, 10);
System.out.println("Character: " + k);
System.out.println("Character: " + ((int) k));
输出:

Character: 1
Character: 49

最简单的方法是使用类型转换:

public char toChar(int c) {
    return (char)c;
}

休斯顿,我们有个问题