I would like to convert a char to its ASCII int value.
I could fill an array with all possible values and compare to that, but it doesn't seems right to me. I would like something like
char mychar = "k"
public int ASCItranslate(char c)
return c
ASCItranslate(k) // >> Should return 107 as that is the ASCII value of 'k'.
The point is atoi()
won't work here as it is for readable numbers only.
It won't do anything with spaces (ASCII 32).
Like, double quotes (" ") are used to declare strings, we use single quotes (' ') to declare characters. Now, to find the ASCII value of ch , we just assign ch to an int variable ascii . Internally, Java converts the character value to an ASCII value. We can also cast the character ch to an integer using (int) .
Very simple. Just cast your char as an int . char character = 'a'; int ascii = (int) character; In your case, you need to get the specific Character from the String first and then cast it.
All you need to do is: int x = (int)character - 48; Or, since the character '0' has the ASCII code of 48, you can just write: int x = character - '0'; // The (int) cast is not necessary.
Do this:-
char mychar = 'k';
//and then
int k = (int)mychar;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With