Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java char array to int

Tags:

java

Is it possible to convert a char[] array containing numbers into an int?

like image 726
Kyle Avatar asked Apr 21 '10 13:04

Kyle


People also ask

Can we convert array to integer in Java?

We can use the parseInt() method and valueOf() method to convert char array to int in Java. The parseInt() method takes a String object which is returned by the valueOf() method, and returns an integer value. This method belongs to the Integer class so that it can be used for conversion into an integer.

How do I convert a char array to a string in Java?

char[] arr = { 'p', 'q', 'r', 's' }; The method valueOf() will convert the entire array into a string. String str = String. valueOf(arr);


2 Answers

Does the char[] contain the unicode characters making up the digits of the number? In that case simply create a String from the char[] and use Integer.parseInt:

char[] digits = { '1', '2', '3' };
int number = Integer.parseInt(new String(digits));
like image 93
Joachim Sauer Avatar answered Oct 11 '22 06:10

Joachim Sauer


Even more performance and cleaner code (and no need to allocate a new String object):

int charArrayToInt(char []data,int start,int end) throws NumberFormatException
{
    int result = 0;
    for (int i = start; i < end; i++)
    {
        int digit = (int)data[i] - (int)'0';
        if ((digit < 0) || (digit > 9)) throw new NumberFormatException();
        result *= 10;
        result += digit;
    }
    return result;
}
like image 40
Thalur Avatar answered Oct 11 '22 07:10

Thalur