Java - 将int更改为ascii

Chr*_*isM 32 java int

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

Sea*_*oyd 62

你想将ints 转换为chars吗?:

int yourInt = 33;
char ch = (char) yourInt;
System.out.println(yourInt);
System.out.println(ch);
// Output:
// 33
// !
Run Code Online (Sandbox Code Playgroud)

或者你想将ints 转换为Strings?

int yourInt = 33;
String str = String.valueOf(yourInt);
Run Code Online (Sandbox Code Playgroud)

或者你的意思是什么?

  • 休斯顿,我们有一个问题 (2认同)

小智 15

如果您首先将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);
Run Code Online (Sandbox Code Playgroud)


Tra*_*vis 5

有很多方法可以将 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();
}
Run Code Online (Sandbox Code Playgroud)

例如,“TEST”的 ASCII 文本可以表示为字节数组:

byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 };
Run Code Online (Sandbox Code Playgroud)

那么你可以执行以下操作:

int value = ByteBuffer.wrap(test).getInt(); // 1413829460
System.out.println(toASCII(value)); // outputs "TEST"
Run Code Online (Sandbox Code Playgroud)

...所以这实际上将 32 位整数中的 4 个字节转换为 4 个单独的 ASCII 字符(每个字节一个字符)。