We can convert an integer to a character

we can convert the character to an integer equivalent to the ASCII value of the same, but can we do the opposite thing, i.e. convert a given ASCII value to its character equivalent?

public String alphabets(int[] num) { char[] s = new char[num.length]; String str = new String(); for(int i=0; i< num.length; i++) { s[i] = 'A' + (char)(num[i]- 1); str += Character.toString(s[i]); } return str; } 

shows a possible loss of error accuracy ...

+6
java
source share
6 answers

To convert to / from:

 int i = 65; char c = (char)i; char c = 'A'; int i = (int)c; 
+8
source share

The error is more complicated than you originally thought, because it is actually the "+" operator, which causes "a possible loss of error accuracy." The error can be resolved if the move is performed:

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


<b> Explanation
The first bullet list of §5.6.2 Binary numeric promotion in the Java Language Specification states that:

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

  • If any of the operands has a reference type, the decompression conversion is performed (Section 5.1.8). Then:
  • If one of the operands 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.

The following bullet list indicates that:

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

  • Multiplicative operators *, / and% (§15.17)
  • Addition and subtraction operators for numeric types + and - (§15.18.2)
  • Numerical comparison operators and> = (§15.20.1)
  • Numerical equality operators == and! = (§15.21.1)
  • Integer bitwise operators &, ^ and | (§15.22.1)
  • In some cases, the conditional operator ?: (§15.25)

In your case, this means:

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

In fact, you don’t even need the cast:

 char c = 126; 

And it really works for Unicode characters. For example, try:

  System.out.println((int) 'โ'); // outputs 3650, a thai symbol char p = 3650; System.out.println(p); // outputs the above symbol 
+5
source share

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.

+3
source share

Does working with char not work?

+1
source share

There are several ways. Take a look at the character wrapper class. Character.digit() can do the trick. This actually does the trick!

 Integer.valueOf('a') 
0
source share

All Articles