Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C – How to split the digits of a number into an array?

If I have a number (long), how can I split its digits into an array?

Example: 4003607001000014 -> [4, 0, 0, 3, 6, 0, 7, 0, 0, 1, 0, 0, 0, 0, 1, 4].

I tried using modulo (n % (10 * i)), where i starts at 1 and its value increases by a multiple of 10 each iteration of a for loop. Then adding the result to the array from n to 0, but this way, any zeros are ignored.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Try dividing the number by 10 each iteration, this is more straightforward than modulo by increasing powers of 10:

unsigned char digits[BIG_ENOUGH];
unsigned long number;
unsigned i = 0;
while (number) {
    digits[i++] = number%10;
    number /= 10;
}

If you need digits[0] to store the most significant digit instead of the least significant digit, reverse the array afterwards:

for (unsigned low = 0, high = digits-1; low < high; low++, high--) {
    unsigned char tmp = digits[low];
    digits[low] = digits[high];
    digits[high] = tmp;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading