====== Fixed-point arithmetic ======
Fixed-point arithmetic provides a way to handle floating point numbers using only simple integer data types. As an example, the value 3.141 could be represented as an integer with a value of 3141 - in this case the value has a fixed-precision of 3 decimal places.
===== String to a fixed-point integer =====
#include
int32_t strntofp(const char *s, char **endptr, size_t n, char dp)
{
int32_t i = 0;
char neg = 0, fp = 0;
if(n <= 0) goto out;
/* Test for a + or - sign */
switch(*s)
{
case '-': neg = !neg;
case '+': s++; n--;
}
/* Read in the number */
while(*s && n && (!fp || dp))
{
char d = *s;
if(d >= '0' && d <= '9')
{
/* Add the digit */
i *= 10;
i += d - '0';
if(fp) dp--;
}
else if(dp > 0 && d == '.') fp = 1;
else break;
/* Next... */
s++;
n--;
}
while(dp > 0)
{
i *= 10;
dp--;
}
/* Fix result if it's negative */
if(neg) i = -i;
out:
/* Set the end pointer if needed */
if(endptr) *endptr = (char *) s;
return(i);
}
===== Fixed-point integer to string =====
#include
#include
const char *fptostr(char *s, size_t n, int32_t value, int8_t dp)
{
int32_t sh;
char i, neg;
neg = value < 0;
if(neg) value = -value;
for(sh = 1, i = 0; i < dp; i++) sh *= 10;
snprintf(s, n, "%s%u.%0*u",
(neg ? "-" : ""),
value / sh, dp,
value % sh);
return(s);
}