Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert array of integers into an integer in C?

Tags:

arrays

c

How can I convert an array of 6 integers into a single integer. Example provided below of what I want to do.

Array: {0, 1, 2, 3, 4, 5, 6}

Integer: 123456

Thank you!

like image 542
Rob Johnson Avatar asked Oct 25 '13 21:10

Rob Johnson


People also ask

How do you convert an array of integers into a single integer in CPP?

Iterate the array and convert the values into string. Then concatenate all of them and convert back to integer. Save this answer.

How do you convert an element to an array in numbers?

Using the parseInt() method The parseInt() method is a built-in function in JavaScript that takes a string as an argument and returns a number. This method can be used to convert an array of strings to an array of numbers.

How do you store digits of a number in an array?

Method 1: The simplest way to do is to extract the digits one by one and print it. Extract the last digit of the number N by N%10, and store that digit in an array(say arr[]). Update the value of N by N/10 and repeat the above step till N is not equals to 0.


2 Answers

Try this:

int i, k = 0;
for (i = 0; i < n; i++)
    k = 10 * k + a[i];

where n is the length of the array. This is true, however, when the array is short enough otherwise you would get an int overflow.

like image 170
sve Avatar answered Dec 08 '22 20:12

sve


Here is a function I made

int array_to_num(int arr[],int n){
    char str[6][3];
    int i;
    char number[13] = {'\n'};

    for(i=0;i<n;i++) sprintf(str[i],"%d",arr[i]);
    for(i=0;i<n;i++)strcat(number,str[i]);

    i = atoi(number);
    return i;
} 

where str[6][3] means there are 6 elements that can hold 2 digit numbers, change it to suit your needs better. Also n is the size of the array you put into the function. Use it like this:

int num[6] = {13,20,6,4,3,55};
int real_num;
real_num = array_to_num(num,6);

real_num will now be 132064355

like image 29
Zeldamaster7778 Avatar answered Dec 08 '22 19:12

Zeldamaster7778