Discussion Forum

sprintf with long?

Next Thread | Thread List | Previous Thread Start a Thread | Settings

DetailsMessage
Read-Only
Author
Holger Warzelhan
Posted
25-Jul-2001 16:29 GMT
Toolset
C166
New! sprintf with long?
Hello,

I am trying to create a string with a variable of type long, using sprintf.
char command [20];
long ofs = 363080;

sprintf (command, "VAL=%d", ofs);
The output string I get is this:
VAL=-30136
which means that the long variable was converted into a short.
Does sprintf not support long types?

Thank you for your help!
Holger
Read-Only
Author
Andrew Neil
Posted
25-Jul-2001 17:49 GMT
Toolset
C166
New! RE: sprintf with long?
In C51, it is very important that you match the type of the actual parameters to the type of the format specifier; eg,
%d is for a signed int;
%u is for an unsigned int;
%Ld is for a signed long;
%Lu is for an unsigned long.

I guess C166 is similar and you need to add the 'L' (not case-sensitive)

Read-Only
Author
Holger Warzelhan
Posted
26-Jul-2001 16:30 GMT
Toolset
C166
New! RE: sprintf with long?
Thank you for your help!
I only looked in a standard C-manual, where there's no such thing as an L.
Of course I didn't think of checking the Keil manual first... sorry for that :)
Holger
Read-Only
Author
Andrew Neil
Posted
27-Jul-2001 09:41 GMT
Toolset
C166
New! RE: sprintf with long?
I only looked in a standard C-manual, where there's no such thing as an L

Hmm... I think you need to throw that manual away and get a proper one!

My ancient K&R (2nd Edition, 1988) says,
"Between the % and the conversion character there may be ... an h if the integer is to be printed as a short, or l if as a long"

It doesn't mention if the h and l are case-sensitive, but in C51 they certainly aren't (I prefer to use the uppercase L, as lowercase l looks too much like the digit 1 in many fonts)

Note that K&R also says that printf, "will get confused, and you will get wrong answers, if there are not enough arguments or if they are the wrong type" (my emphasis)

Next Thread | Thread List | Previous Thread Start a Thread | Settings