Convert Long to String

How do I convert a long to a string? Example code below:

test ID

unsigned long testID = 1716526225;
sprintf(buf, "GET /testID=%d HTTP/1.0", testID);

Output is: GET /testID=0 HTTP/1.0

Any ideas?

How do I convert an unsigned long to a string?

unsigned long testID = 1716526225;
sprintf(buf, "GET /testID=[glow]%lu[/glow] HTTP/1.0", testID);

hmmm... that doesn't seem to work. I get the following results:

GET /testID=7313 HTTP/1.0

Should be:

GET /testID= 1716526225 HTTP/1.0

Works fine for me...

void setup( void )
{
  Serial.begin( 57600 );
}

void loop( void )
{
  char buf[50];
  
  unsigned long testID = 1716526225;
  sprintf(buf, "GET /testID=%lu HTTP/1.0", testID); 
  Serial.println( buf );
  delay( 1000 );
}
GET /testID=1716526225 HTTP/1.0
GET /testID=1716526225 HTTP/1.0
GET /testID=1716526225 HTTP/1.0
GET /testID=1716526225 HTTP/1.0
GET /testID=1716526225 HTTP/1.0

Instead of calling sprintf you could also use ltoa which consumes less resources and use the Streaming library if a single line or string concatenation is desired.

Code snippet:

  char buf[50];
  
  unsigned long testID = 1716526225;
  ltoa(testID, buf, 10);  // 10 is the base value not the size - look up ltoa for avr
  Serial << "GET /testID=" << testID << " HTTP/1.0" << endl; // Streaming.h
  delay( 1000 );

or

  char buf[50];
  
  unsigned long testID = 1716526225;
  ltoa(testID, buf, 10);  // 10 is the base value not the size - look up ltoa for avr
  Serial.print("GET /testID=");
  Serial.print(testID);
  Serial.println(" HTTP/1.0");
  delay( 1000 );

Cheers,

Eric