0

So what i understand is that if for example i have an int a = 49 and want to find out the ASCII equivalent to it, all i need to do is:

 int a = 49; 
 System.out.println((char)a);

which has the Output: 1.

But how can i do this reversed? So lets say i have int a = 1 and i want the output to be 49?

I have already tried stuff like:

int a = 1; 
System.out.println ((char)a);

But the output here is "." instead of 49.

  • You probably want to use `1` as `char` which means `'1'`. – Pshemo Apr 15 '21 at 16:48
  • ok yeah but if im given an int with the value 1 how do i turn it into a char with value "1"? – Liebertosan Apr 15 '21 at 16:50
  • Since numerical chars in Unicode Table are in order from 0 to 9 you can just use digit under `a` to move from `'0'` character `a` amount of times. For instance `'0' + 0` would return index of `'0'`. `'0' + 1` would return index of `'1'`. All you need to do with that index is convert it back to `char`. So you can write something like `int a = 1; char ch = (char)('0'+a);`. – Pshemo Apr 15 '21 at 16:54
  • You can also use easier way :) `char ch = Character.forDigit(a, 10);`. – Pshemo Apr 15 '21 at 16:55

1 Answers1

0

This:

int a = 49;  
System.out.println((char)a);  

gives you the char whose internal value is 49, which is to say the unicode character '1'. There is no numerical conversion going on, it's just two ways to look at the same number.

In this:

int a = 1; 
System.out.println((char)a);

you get the char whose internal value is 1, which is a unicode control character (ctrl/A, which probably won't be printed in any useful way). There is nothing there that can magically come up with the value 49.

If you had the character '1' then it's easy:

int a = '1';  
System.out.println(a);  

but this is practically the same as your first case; '1' and 49 are the same value.

user15187356
  • 807
  • 3
  • 3