Long to char conversion

Hi

I’m trying to convert sensor values (mostly large integers) into character strings for use with the virtualwire library, but I can’t seem to get this to work using either itoa and sprintf functions. Here is some simple test code I wrote:

#include <stdio.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(9, 8, 7, 6, 5, 4);
long testval = 100000;
char buffer [50];
char buffer1 [50]; 

void setup() {
  lcd.begin (20,4);
  lcd.clear (); 
}

void loop() {
  itoa(testval, buffer, 10);       
  sprintf(buffer1, "%d", testval);
  lcd.clear();
  lcd.home();
  lcd.print ("1st = ");
  lcd.print (testval); 
  lcd.setCursor (0,1);
  lcd.print ("2nd = ");
  lcd.print (buffer);   
  lcd.setCursor (0,2);
  lcd.print ("2nd = ");
  lcd.print (buffer1);   
  delay(2000);
}

However, the string conversion result for testval = 1000000 comes out as -31072. Any help would be appreciated!

gadget

The itoa function expects an integer argument. The ltoa (long to ascii) might be more useful.

The %d format specifier tells sprintf that it is dealing with an integer. The %ld format specifier tells sprintf that it is dealing with a long.

Both %ld and ltoa did the trick - thanks so much!

I should have looked more closely at the sprintf format references! It all seems so obvious now that you pointed it out! [Smacks head with palm]

gadget