Files
VCCPlusOSS/sdk/cmoc/compat/fixed.c
T

70 lines
2.5 KiB
C

// SPDX-License-Identifier: GPL-3.0-or-later
#include <cmoc.h>
#include <vcc/decimal.h>
// A nonzero BASIC float has magnitude M * 2^(exponent - 160), where M is
// its unsigned 32-bit significand with an implicit leading one. Scaling M
// by 5^places is exact in five bytes; the remaining factor is a power of two.
static unsigned long roundedUnits(const unsigned char *packed, unsigned char places)
{
unsigned exponent = packed[0];
if (!exponent) return 0UL;
unsigned shift = 159 - exponent - places; // Keep one extra bit for rounding.
if (shift >= 40) return 0UL;
unsigned char product[5];
product[0] = 0;
product[1] = packed[1] | 0x80;
memcpy(product + 2, packed + 2, 3);
for (unsigned step = 0; step < places; ++step) {
unsigned carry = 0;
for (unsigned i = sizeof(product); i > 0; --i) {
unsigned part = (unsigned) product[i - 1] * 5 + carry;
product[i - 1] = (unsigned char) part;
carry = part >> 8;
}
}
// Within the accepted range shift is at least 12, so at most four
// bytes contribute. Bit zero after shifting is the half-unit bit.
unsigned bytes = sizeof(product) - shift / 8;
unsigned long units = 0UL;
for (unsigned i = 0; i < bytes; ++i)
units = (units << 8) | product[i];
units >>= shift % 8;
return (units + 1UL) >> 1;
}
int vcc_fixed(char *dest, unsigned capacity, float value, unsigned char places)
{
const unsigned char *packed = (const unsigned char *) &value;
if (capacity && !dest) return -1;
if (places > 3 || packed[0] > 144) { // Exponent 145 begins at 65536.
if (capacity) dest[0] = '\0';
return -1;
}
unsigned long units = roundedUnits(packed, places);
char digits[11]; // Room for a decimal unsigned long and its terminator.
ultoa10(units, digits);
int count = strlen(digits);
int point = count - (int) places;
char text[10]; // Longest possible output is "-65536.000", before the NUL.
unsigned length = 0;
if (units && (packed[1] & 0x80)) text[length++] = '-';
if (point <= 0) text[length++] = '0';
for (int i = 0; i < point; ++i) text[length++] = digits[i];
if (places) {
text[length++] = '.';
for (int i = point; i < count; ++i)
text[length++] = i < 0 ? '0' : digits[i];
}
if (capacity) {
unsigned stored = length < capacity ? length : capacity - 1;
memcpy(dest, text, stored);
dest[stored] = '\0';
}
return (int) length;
}