Reputation: 349
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
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
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
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
Reputation: 8839
int i;
int x = 0;
for ( i = 0; i < 4; i++ )
x = ( 10 * x + number[i] );
Upvotes: 2
Reputation: 9601
int i = 0, x = 0;
for(; i < arrSize; i++)
x = x * 10 + number[i];
x
is the result.
Upvotes: 2
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
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