2011-03-16 207 views

回答

47

你想int秒值进行转换,以char小号?:

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

或者你想int秒值进行转换,以String S'

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

这是什么意思?

14

如果您首先将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); 
1

事实上,在过去的答案 字符串strAsciiTab = Character.toString((char)的iAsciiValue); 必不可少的部分是(char)iAsciiValue它正在做的工作(Character.toString无用)

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

如果yourint = 49(或0X31),CH将是“1”

2

有很多方式为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(); 
} 

例如,对于 “TEST” 的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字符(每字节一个字符)。

1

在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)); 
} 
0

您可以在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