I know it's may be an basic question. But I want to be clear. If I have a java char c which has value '9', can I convert it to int by doing following: c - '0' ? I used to play this and never had problem but someone told it's wrong? And why ?
I don't think it's wrong, you can do it.
int x = '9' - '0';
But if you also want it to work for hexadecimal chars 'A' = 10, 'B' = 11, etc you can do it like this
int x = Character.getNumericValue('9');
Edit: based on other answer in this post Character.getNumericValue will actually go all the way to 'Z' = 35, so if you want to be safe use
int x = Character.digit('9', 10); // for base 10
int x = Character.digit('9', 16); // for base 16
int x = Character.digit('B', 16); // for base 16
Yes, you can. But, I would strongly recommend you use Character.digit(char, int)
(where the int
is the radix), something like
char ch = '9';
int i = Character.digit(ch, 10);
System.out.printf("ch = %c, i = %d%n", ch, i);
The only issue(s) I see with your approach is that it is a little more complicated, and you should validate the range
if (ch >= '0' && ch <= '9')
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