First, the format string in your sprintf() needs the long specifier. In the code below, the sprintf() function compiles to 3576 bytes. The ltoa() version compiles to 2254 bytes:
void setup() {
// put your setup code here, to run once:
char buffer[15];
long val = 4572516;
Serial.begin(9600);
// sprintf(buffer, "%09lX", (long)val); // Use the long specificer before the 'X'
ltoa(val, buffer, 16);
Serial.println(buffer);
}
void loop() {
// put your main code here, to run repeatedly:
}
sprintf() is a very powerful function, but rarely does one program use all of that power. You're usually better off using one of the *toa() functions. See:
PaulS:
But why is it necessary to cast a long to a long?
It isn't. I was experimenting to see if sprintf() was smart enough to convert from int to long if the variable was cast to a long. It isn't. I forgot to remove it.
Parameters
val: a variable to format as a String - string, char, byte, int, long, unsigned int, unsigned long, float, double [emphasis added]
base (optional) - the base in which to format an integral value
Examples
All of the following are valid declarations for Strings.
...
String stringOne = String(45, HEX);
So, it looks like that construction is valid for an integer, and it looks like the constructor can manage long's and unsigned long's. I can't find anything wrong with it. Can you elaborate?
econjack:
First, the format string in your sprintf() needs the long specifier. In the code below, the sprintf() function compiles to 3576 bytes. The ltoa() version compiles to 2254 bytes: