Tuesday 25 July 2017

c - Integers >9999 in PIC C18


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?



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 
uint32_t start = 1;

No comments:

Post a Comment

arduino - Can I use TI&#39;s cc2541 BLE as micro controller to perform operations/ processing instead of ATmega328P AU to save cost?

I am using arduino pro mini (which contains Atmega328p AU ) along with cc2541(HM-10) to process and transfer data over BLE to smartphone. I...