NO

Author Topic: gcvtw double to wide string  (Read 3188 times)

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2115
gcvtw double to wide string
« on: October 20, 2017, 11:46:48 AM »
gcvtw convert double to wide string in small scale.
Code: [Select]
#include <stdio.h>
#include <wchar.h>

wchar_t *gcvtw(double f, int ndigit, wchar_t *buf)
{
int i;
unsigned long long z, k;
wchar_t *c = buf;
double f2, t, scal;
int sign = 0;

if ((int)ndigit == -1)
ndigit = 5;

if (ndigit > 18) // 20 ?
ndigit = 18;

if (f < 0.0) {
sign = 1;
f = -f;
buf++;
}

scal = 1;
for (i = ndigit; i > 0; i--)
scal *= 10;
k = f + 0.1 / scal;
f2 = f - k;
if (!f) {
(*(buf++) = ('0'));
if (ndigit > 0)
(*(buf++) = ('.'));
for (i = 0; i < ndigit; i++)
(*(buf++) = ('0'));
(*(buf++) = (0));
return c;
}

i = 1;
while (f >= 10.0) {
f /= 10.0;
i++;
}

buf += i + ndigit + 1;

(*(buf--) = (0));

if (ndigit > 0) {
t = f2 * scal;
z = t + 0.5;
for (i = 0; i < ndigit; i++) {
(*(buf--) = ('0' + (z % 10)));
z /= 10;
}
(*(buf--) = ('.'));
} else
(*(buf--) = (0));

do {
(*(buf--) = ('0' + (k % 10)));
k /= 10;
} while (k);

if (sign)
(*(buf--) = ('-'));
return c;
}

int main(void)
{
wchar_t s[80];
double d = 1.2345678901234567890;
long long* pll = (long long*)&d;
*pll = 0x3FF3C0CA428C59FB;
// double d = 3.14159265358979323846264338327;
// printf("%p\n", *(long long*)&d);
gcvtw(d, 18, s);
// puts("3.14159265358979323846264338327");
fputws(s,stdout);
return 0;
}
original gcvt source unknown.
similar code
« Last Edit: October 21, 2017, 11:36:53 AM by TimoVJL »
May the source be with you