2011-03-16 10 views

risposta

47

Vuoi convertire int s per char s ?:

int yourInt = 33; 
char ch = (char) yourInt; 
System.out.println(yourInt); 
System.out.println(ch); 
// Output: 
// 33 
// ! 

O vuoi convertire int s per String s?

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

O cosa intendi?

14

Se per prima cosa si converte l'int in un char, si avrà il codice ASCII.

Ad esempio:

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); 
1

Infatti nell'ultima risposta String strAsciiTab = Character.toString ((char) iAsciiValue); la parte essenziale è (char) iAsciiValue che sta facendo il lavoro (Character.toString inutile)

Significato la prima risposta è stata corretta in realtà char ch = (char) yourInt;

se in yourint = 49 (o 0x31), ch sarà '1'

2

Ci sono molti modi per convertire un int in ASCII (a seconda delle esigenze), ma qui è un modo per convertire ogni byte intero ad un carattere 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(); 
} 

ad esempio, il testo ASCII per "TEST" può essere rappresentato come l'array di byte:

byte[] test = new byte[] { (byte) 0x54, (byte) 0x45, (byte) 0x53, (byte) 0x54 }; 

allora si potrebbe effettuare le seguenti operazioni:

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

... quindi questo converte essenzialmente i 4 byte in un numero intero a 32 bit in 4 caratteri ASCII separati (un carattere per byte).

1

In Java, si desidera utilizzare veramente Integer.toString per convertire un numero intero nel valore String corrispondente. Se avete a che fare con solo le cifre 0-9, allora si potrebbe usare qualcosa di simile:

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]; 
} 

o, equivalentemente:

private static int ASCII_ZERO = 0x30; 

private static char getDigit(int digitValue) { 
    assertInRange(digitValue, 0, 9); 
    return ((char) (digitValue + ASCII_ZERO)); 
} 
0

È possibile convertire un numero in ASCII in java. esempio convertendo un numero 1 (base è 10) in ASCII.

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

uscita:

Character: 1 
Character: 49