Eagle
Eagle

Reputation: 349

Converting an int array to an int value in c

I have an integer array

int number[] = {1,2,3,4};

What can I do to get int x = 1234? I need to have a c version of it.

Upvotes: 4

Views: 216

Answers (7)

Floris
Floris

Reputation: 46375

x = 1000*number[0] + 100*number[1] + 10*number[2] + number[3];

This is basically how decimal numbers work. A more general version (when you don't know how long 'number' is) would be:

int x = 0;
int base = 10;
for(int ii = 0; ii < sizeof(number); ii++) x = base*x + number[ii];

Note - if base is something other than 10, the above code will still work. Of course, if you printed out x with the usual cout<<x, you would get a confusing answer. But it might serve you at some other time. Of course you would really want to check that number[ii] is between 0 and 9, inclusive - but that's pretty much implied by your question. Still - good programming requires checking, checking, and checking. I'm sure you can add that bit yourself, though.

Upvotes: 10

Bob Cromwell
Bob Cromwell

Reputation: 445

Answer is quite easy.Just list a complete function here.

int toNumber(int number[],arraySize)
{
   int i;
   int value = 0;
   for(i = 0;i < arraySize;i++)
   {
      value *=10;
      value += number[i];
   }
   return value;
}

Upvotes: 1

Ultima
Ultima

Reputation: 31

int number[]={1,2,3,4}
int x=0,temp;
temp=10;
for(i=0;i<number.length;i++)
    {
        x=x*temp+number[i];
    }
cout>>x;

Upvotes: 2

unxnut
unxnut

Reputation: 8839

int i;
int x = 0;
for ( i = 0; i < 4; i++ )
    x = ( 10 * x + number[i] );

Upvotes: 2

johnchen902
johnchen902

Reputation: 9601

int i = 0, x = 0;
for(; i < arrSize; i++)
    x = x * 10 + number[i];

x is the result.

Upvotes: 2

anthony sottile
anthony sottile

Reputation: 69914

You can think of how to "shift over" a number to the left by multiplying by ten. You can think of appending a digit by adding after a shift.

So you effectively end up with a loop where you do total *= 10 and then total += number[i]

Of course this only works if your array is digits, if it is characters you'll want to do number[i] - '0' and if it is in a different base you'll want to multiply by a different number (8 for instance if it is octal).

Upvotes: 2

Daniel
Daniel

Reputation: 1087

You could do something with a for loop and powers of 10

int tens = 1;
int final = 0;
for (int i = arrSize - 1; i <= 0; ++i)
{
    final += tens*number[i];
    tens*=10;
}
return final;

Upvotes: 1

Related Questions