Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an int array to an int value in c

Tags:

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.

like image 849
Eagle Avatar asked Nov 30 '22 03:11

Eagle


2 Answers

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.

like image 183
Floris Avatar answered Dec 18 '22 05:12

Floris


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

like image 20
Anthony Sottile Avatar answered Dec 18 '22 06:12

Anthony Sottile