Converting integer into array of digits

c, c++

Solution

Just using something like this:

int n = 544; // your number (this value will Change so you might want a copy)
int i = 0; // the array index
char a[256]; // the array

while (n) { // loop till there's nothing left
    a[i++] = n % 10; // assign the last digit
    n /= 10; // "right shift" the number
}

Note that this will result in returning the numbers in reverse order. This can easily be changed by modifying the initial value of `i` as well as the increment/decrement based on how you'd like to determine to length of the value.

(Brett Hale) I hope the poster doesn't mind, but I thought I'd add a code snippet I use for this case, since it's not easy to correctly determine the number of decimal digits prior to conversion:

{
    char *df = a, *dr = a + i - 1;
    int j = i >> 1;

    while (j--)
    {
        char di = *df, dj = *dr;
        *df++ = dj, *dr-- = di; /* (exchange) */
    }
}

Problem

I need to convert two integers into two arrays of digits, so for example 544 would become `arr[0] = 5, arr[1] = 4, arr[2] = 4`. I have found some algorithms doing this, but they create new array, and return this. I would have to allocate this memory for two arrays, so I wanna pass two integers by reference and do this on them directly. I guess I can do this, because these integers are in fact template types, so they should be changeable. That's why I added C++ tag here.

Original source