Search code examples
arrayscmodulolong-long

Buggy transfer of single long long numbers to int array


I’m trying to grab a Long Long Int and split each place number into it’s own spot in an array, in order of course, with array[0] being the largest number.

So for instance, if the number was 314, then array[0] = 3, array[1] =1, and array[2] = 4.

This is part of a calculator project for a microcontroller where I’m writing the graphics library (for fun) and using arrays to display each line.

The issue is, it needs to be able to deal with really large numbers (9,999,999,999+), and I’m having dramas with the large stuff. If the Long Long is < 1,000,000, it will writes all the numbers perfectly, but the more numbers I add, they all start to be written wrong towards the end.

For instance, 1,234,567,890 displays as 1,234,567,966.

Here’s the snippet of code I’m using:

long long int number = 1234567890;
int answerArray[10];
int numberLength = 10;

for(writeNumber = 0; writeNumber < numberLength; writeNumber++)
{
    answerArray[writeNumber] = ((int)(number / pow(10, (numberLength - 1 - writeNumber))) % 10;
}

I’m fairly sure this has to do with either the “%” and multiple data types, because any number within the Int range works perfectly.

Can you see where I’m going wrong? Is there a better way achieve my goal? Any tips for large numbers?


Solution

  • Your issue is that you're casting what is potentially a very large number to an int. Look at the iteration when writeNumber is numberLength-1. In that case, you're dividing a long long by 1 and then forcing the result into an int. Once number becomes larger than 2^31-1, you're going to run into problems.

    You should remove the cast altogether as well as the call to pow. Instead, you should iteratively grab the next digit by modding out by 10 and then dividing number (or a copy of it) by 10.

    E.g.,

    int index = sizeof(answerArray)/sizeof(answerArray[0]);
    for (long long x=number; x>0; x /= 10) {
        answerArray[--index] = x%10;
    }