Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Char to Integer [duplicate]

Tags:

java

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 ?

like image 854
user2372074 Avatar asked Dec 26 '22 04:12

user2372074


2 Answers

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
like image 174
Gonen I Avatar answered Jan 14 '23 04:01

Gonen I


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') 
like image 34
Elliott Frisch Avatar answered Jan 14 '23 03:01

Elliott Frisch