can we convert integer into character

后端 未结 6 1652
北海茫月
北海茫月 2020-12-19 08:06

we can convert character to an integer equivalent to the ASCII value of the same but can we do the reverse thing ie convert a given ASCII value to its character equivalent?

相关标签:
6条回答
  • 2020-12-19 08:37

    To convert to/from:

    int i = 65;
    char c = (char)i;
    
    char c = 'A';
    int i = (int)c;
    
    0 讨论(0)
  • 2020-12-19 08:50

    Character.toChars:

    public static char[] toChars(int codePoint)
    

    Converts the specified character (Unicode code point) to its UTF-16 representation stored in a char array.

    0 讨论(0)
  • 2020-12-19 08:50

    Doesn't casting to char work?

    0 讨论(0)
  • 2020-12-19 08:57

    You actually don't even need a cast:

    char c = 126;
    

    And this actually appears to work for unicode characters as well. For example try:

     System.out.println((int) 'โ'); // outputs 3650, a thai symbol
     char p = 3650;
     System.out.println(p); // outputs the above symbol
    
    0 讨论(0)
  • 2020-12-19 08:59

    There are several ways. Look at the Character wrapper class. Character.digit() may do the trick. Actually this does the trick!!

    Integer.valueOf('a')
    
    0 讨论(0)
  • 2020-12-19 09:01

    The error is more complex than you would initially think, because it is actually the '+' operator that causes the "possible loss of precision error". The error can be resolved if the cast is moved:

    s[i] = (char)('A' + (num[i]- 1));


    Explanation
    In the first bullet list of §5.6.2 Binary Numeric Promotion in the Java Language Specification it is stated that:

    When an operator applies binary numeric promotion to a pair of operands [...] the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:

    • If any of the operands is of a reference type, unboxing conversion (§5.1.8) is performed. Then:
    • If either operand is of type double, the other is converted to double.
    • Otherwise, if either operand is of type float, the other is converted to float.
    • Otherwise, if either operand is of type long, the other is converted to long.
    • Otherwise, both operands are converted to type int.

    In the next bullet list it is stated that:

    Binary numeric promotion is performed on the operands of certain operators:

    • The multiplicative operators *, / and % (§15.17)
    • The addition and subtraction operators for numeric types + and - (§15.18.2)
    • The numerical comparison operators , and >= (§15.20.1)
    • The numerical equality operators == and != (§15.21.1)
    • The integer bitwise operators &, ^, and | (§15.22.1)
    • In certain cases, the conditional operator ? : (§15.25)

    In your case, that translates to:

    s[i] = (int)'A' + (int)((char)(num[i] - (int)1));
    hence the error.

    0 讨论(0)
提交回复
热议问题