![](templates/subSilver/images/CCSLogo.jpg) |
![CCS C Software and Maintenance Offers](templates/subSilver/images/forumAd6.jpg) |
View previous topic :: View next topic |
Author |
Message |
future
Joined: 14 May 2004 Posts: 330
|
Printf decimal point on signed integers |
Posted: Sat Sep 30, 2006 3:07 pm |
|
|
Hi,
I an trying to convert a 16bit signed integer to a string and insert a decimal point.
The format I want is:
+1.5
+1.0
+0.5
0.0
-0.5
-1.0
...
What I am getting is:
+0.5
+0.0
+0.-5
-1.0
-1.-5
char *cnv_b2( signed long variable, char *string )
{
memset( string, 0, 6 );
sprintf( string, "%+1d.%01d", variable/2, 5*(variable%2) );
return( string );
}
Is there a good way to convert integers to other fractions (0.1, 0.2, 0.5...) also?
Thank you. |
|
![](templates/subSilver/images/spacer.gif) |
bls
Joined: 30 Sep 2006 Posts: 4
|
|
Posted: Sat Sep 30, 2006 3:19 pm |
|
|
Something like this will work for your examples of scaling by 2, 5 and 10:
Code: |
conv(int i, char *buf, int scale)
{
if (i != 0) {
if (i < 0) { *buf = '-'; i = -i; }
else { *buf = '+';}
buf++;
}
sprintf(buf, "%d.%d", i/scale, (10/scale)*(i%scale));
}
|
|
|
![](templates/subSilver/images/spacer.gif) |
bls
Joined: 30 Sep 2006 Posts: 4
|
Slightly tidier version... |
Posted: Sat Sep 30, 2006 4:17 pm |
|
|
Use ldiv instead of doing division and remainder separately; fix sprintf formatting so it actually works on CCS C:
Code: |
void conv(signed long i, char *buf, int scale)
{
ldiv_t x;
int frac;
x = ldiv(i, (signed long) scale);
if (i != 0) {
if (i < 0) { *buf = '-'; i = -i; }
else { *buf = '+';}
buf++;
}
frac = (int)x.rem * 10 / scale;
sprintf(buf, "%ld.%d", x.quot, frac);
}
|
|
|
![](templates/subSilver/images/spacer.gif) |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|