Electronic – Integers >9999 in PIC C18

cc18compilerpicsoftware

In this answer, I made a function to convert an integer to an ASCII string:

void writeInteger(unsigned int input) {
    unsigned int start = 1;
    unsigned int counter;
    while (start <= input)
        start *= 10;
    for (counter = start / 10; counter >= 1; counter /= 10)
        serialWrite(((input / counter) % 10) + 0x30);
}

I tested this function with a loop:

unsigned int counter;
for (counter = 0; counter< 1000000; counter++) {
    writeInteger(counter);
    serialWrite('\r');
    serialWrite('\n');
}

This works, for \$1\le{}n\le9999\$. However, for 10,000 and above, I'm getting weird strings on the terminal:

10000 => 2943
10001 => 2943
10002 => 2944
10003 => 2944
10004 => 2944
10005 => 2945
...

Why is that? How can I fix it?

Best Answer

It's because the following section of code will be trying to set start to 100,000 for numbers equal to or above 10,000 which is too big for an unsigned int which is a 16-bit and can only hold 0-65535:

while (start <= input)
    start *= 10;

Changing the definition to the following should fix it:

unsigned long start = 1;

Another alternative to make the code clearer is to include stdint.h so it may be defined as the following that will work across compilers:

#include <stdint.h>
uint32_t start = 1;