Kyle
Kyle

Reputation: 763

Java char array to int

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

Upvotes: 14

Views: 108244

Answers (6)

Nuwan Samarasinghe
Nuwan Samarasinghe

Reputation: 153

It is possible to convert a char[] array containing numbers into an int. You can use following different implementation to convert array.

  1. Using Integer.parseInt

    public static int charArrayToInteger(char[] array){
        String arr = new String(array);
        int number = Integer.parseInt(arr);
    
        return number;
    }
    
  2. Without Integer.parseInt

    public static int charArrayToInt(char[] array){
        int result = 0;
        int length = array.length - 1;
    
        for (int i = 0; i <= length; i++)
        {
             int digit = array[i] - '0'; //we don't want to cast by using (int)
             result *= 10;
             result += digit;
        }
        return result;
    }
    

Example:

 public static void main(String []args){
    char[] array = {'1', '2', '3', '4', '5'};
    int result = 0;

    result = charArrayToInteger(array);
    System.out.println("Using Integer.parseInt: " + result);

    result = charArrayToInt(array);
    System.out.println("Without Integer.parseInt: " + result);

 }

Output:

Using Integer.parseInt: 12345
Without Integer.parseInt: 12345

Upvotes: 2

NAITIK GADA
NAITIK GADA

Reputation: 39

Well, you can try even this

    char c[] = {'1','2','3'};
    int total=0,x=0,m=1;
    for(int i=c.length-1;i>=0;i--)
    {
        x = c[i] - '0';
        x = x*m;
        m *= 10;
        total += x;
    }
    System.out.println("Integer is " + total);

Upvotes: 0

Ajay Rathore
Ajay Rathore

Reputation: 81

char[] digits = { '0', '1', '2' };
int number = Integer.parseInt(String.valueOf(digits));

This also works.

Upvotes: 8

Thalur
Thalur

Reputation: 1163

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;
}

Upvotes: 11

Nikita Koksharov
Nikita Koksharov

Reputation: 10783

Another way with more performance:

char[] digits = { '1', '2', '3' };

int result = 0;
for (int i = 0; i < chars.length; i++) {
   int digit = ((int)chars[i] & 0xF);
   for (int j = 0; j < chars.length-1-i; j++) {
        digit *= 10;
   }
   result += digit;
}

Upvotes: 1

Joachim Sauer
Joachim Sauer

Reputation: 308021

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));

Upvotes: 28

Related Questions