Regarding single precision floating point format, wikipedia has god a really good page explaining it for anyone reading the thread wanting a decent explanation.
http://en.wikipedia.org/wiki/Single_precision" rel="nofollow" target="_blank
http://en.wikipedia.org/wiki/Single_precision
This same issue arose recently at work and i think i talked a colleague around to just doing it the way celsoken described.
JD
Here is an implementation of float to message,the total size in bytes is: reverse 102+ itoa 108+ ftoaMsg 165 + strcpy 41. Much less than sprintf("5f) which is around 2500byte. However, there is a fixed predetermined amount of decimal positions.
you can call the functions as such:
ftoaMsg(senderBufferPtr, "vrms=", 1234.123 , 2);
/* reverse: reverse string s in place */
void reverse(char s[])
{
int i, j;
char c;
for (i = 0, j = strlen(s)-1; i<j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/*
itoa = 143 byte
reverse = 102 byte
*/
void itoa(long int n, char s[])
{
long int i, sign;
if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
void ftoaMsg(char *Buffer, char *Msg, float Number, unsigned char decimalPrecision)
{
long int numf;
unsigned char dp,strSize;
char * ptr;
Number = Number * 100;
numf = (long int) Number;
(void) strcpy(Buffer, Msg);
itoa ( numf, &Buffer[strlen(Msg)] );
strSize= strlen(Buffer)+1;
ptr = &Buffer[strSize];
for (dp=0;dp<decimalPrecision+1; dp++) //decimal previsions + 1 null termination;
{
*ptr = *(ptr-1);
ptr--;
}
*ptr = '.';
return;
}
Hi,
My previous implementation had some bugs in it... please use this implementation:
Here is how you can call the functions:
unsigned char senderBufferPtr[100];
ftoaMsg(senderBufferPtr, "thenumberis=" , 125.123123 , 2);
the code:
void ftoaMsg(char *Buffer, char *Msg, float Number, unsigned char decimalPrecision)
{
long int numf;
unsigned char strSize;
char * ptr;
(void) strcpy(Buffer, Msg);
strSize= strlen(Buffer);
ptr = &Buffer[strSize];
ftoa( Number, decimalPrecision , ptr);
return;
}
const float ROUND[6]={0.49,0.05,0.005,0.0005,0.00005,0.000005};
void ftoa(float fnum, unsigned char decimals, unsigned char *str)
{
float scale;
unsigned char u1,u2;
if (fnum<0.0)
{
fnum=-fnum;
*str++='-';
}
if (decimals>5)
decimals=5;
fnum += ROUND[decimals];
u1=0;
scale=1.0;
while (fnum>=scale)
{
scale *= 10.0;
++u1;
}
if (u1==0)
*str++='0';
else
while (u1--)
{
scale=floor(0.5+scale/10.0);
u2=(unsigned char)(fnum/scale);
*str++=u2+'0';
fnum -= scale*u2;
}
if (decimals==0)
{
*str=0;
return;
}
*str++='.';
while (decimals--)
{
fnum *= 10.0;
u2=(unsigned char) fnum;
*str++ = u2+'0';
fnum -= u2;
}
*str=0;
}