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!
Iterate the array and convert the values into string. Then concatenate all of them and convert back to integer. Save this answer.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With