Bug in print(

Have been playing / modifying the print() function (~arduino-0021\hardware\arduino\cores\arduino\print.cpp) today and I came accross a bug in the private printNumber(). If one calls e.g. Serial.print(10,1) it will come in an endless loop. base 0 is also not wanted.

void Print::printNumber(unsigned long n, uint8_t base)
{
  unsigned char buf[8 * sizeof(long)]; // Assumes 8-bit chars. 
  unsigned long i = 0;

  if (n == 0) {
    print('0');
    return;
  } 

[glow]  while (n > 0) {
    buf[i++] = n % base;
    n /= base;
  }[/glow]

  for (; i > 0; i--)
    print((char) (buf[i - 1] < 10 ?
      '0' + buf[i - 1] :
      'A' + buf[i - 1] - 10));
}

A few lines could capture this bug with an errormessage or force it to acceptable behavior. Imho the latter is preferred as it uses smalles footprint. (To be inserted before the while)

if (base <2) base = 10; // forced base

OK one should test the value of before calling the print function, but a typo causing endless loops makes me drink too much coffee :slight_smile:

Footnote
Base 1 makes sense in some apps. NB in base 1 the number 5 can be written as 11111, the number 3 as 111, 17 as 11111111111111111. Sometimes every fifth line is a strike through so 17 becomes 1111 1111 1111 11. Base 1 numbers have the remarkable property that the time used processing them is linear with their size, e.g you will definitely run out of paper when printing MAXLONG in base 1.

Nice finding.

However, I would prefer to throw a warning/error than forcing a base of 10 ;D

Base 1 makes me remember the turing machine :D

OK, something like below? takes a few more bytes. Think it should at least be documented.

if ((base <2) || (base > 36))   // base can be too big too
{
  print("Base Error: );
  print(base);
  return;
}

Well, I don't mean a direct warning in runtime, I mean a warning in compilation time like:

Warning #1: Base can't be 0, using base 10 as default

;D

I mean a warning in compilation time like

Since warnings are disabled by default, does this buy you anything?