CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

Printf decimal point on signed integers

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
future



Joined: 14 May 2004
Posts: 330

View user's profile Send private message

Printf decimal point on signed integers
PostPosted: Sat Sep 30, 2006 3:07 pm     Reply with quote

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.
bls



Joined: 30 Sep 2006
Posts: 4

View user's profile Send private message

PostPosted: Sat Sep 30, 2006 3:19 pm     Reply with quote

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));
}
bls



Joined: 30 Sep 2006
Posts: 4

View user's profile Send private message

Slightly tidier version...
PostPosted: Sat Sep 30, 2006 4:17 pm     Reply with quote

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);
}
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
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