aboutsummaryrefslogtreecommitdiff
path: root/libs/libc/conv.c
blob: 72a919bba6f331e390ea4e6916fb4bf09b59775f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
// MIT License, Copyright (c) 2020 Marvin Borner

#include <conv.h>
#include <def.h>
#include <math.h>
#include <mem.h>
#include <str.h>

int itoa(s32 value, char *buffer, u32 base)
{
	char tmp[16];
	char *tp = tmp;
	int i;
	unsigned v;

	int sign = (base == 10 && value < 0);
	if (sign)
		v = -value;
	else
		v = (unsigned)value;

	while (v || tp == tmp) {
		i = v % base;
		v /= base;
		if (i < 10)
			*tp++ = i + '0';
		else
			*tp++ = i + 'a' - 10;
	}

	int len = tp - tmp;

	if (sign) {
		*buffer++ = '-';
		len++;
	}

	while (tp > tmp)
		*buffer++ = *--tp;
	*buffer = '\0';

	return len;
}

static int normalize(f64 *val)
{
	int exp = 0;
	double value = *val;

	while (value >= 1.0) {
		value /= 10.0;
		++exp;
	}

	while (value < 0.1) {
		value *= 10.0;
		--exp;
	}
	*val = value;
	return exp;
}

char *ftoa(f64 value, char *buffer, u32 width)
{
	int exp = 0;
	u32 loc = 0;

	if (value == 0.0) {
		buffer[0] = '0';
		buffer[1] = '\0';
		return buffer;
	}

	if (value < 0.0) {
		*buffer++ = '-';
		value = -value;
	}

	exp = normalize(&value);

	while (exp > 0) {
		int digit = value * 10;
		*buffer++ = digit + '0';
		value = value * 10 - digit;
		++loc;
		--exp;
	}

	if (loc == 0)
		*buffer++ = '0';

	*buffer++ = '.';

	while (exp < 0 && loc < width) {
		*buffer++ = '0';
		--exp;
		++loc;
	}

	while (loc < width) {
		int digit = value * 10.0;
		*buffer++ = digit + '0';
		value = value * 10.0 - digit;
		++loc;
	}
	*buffer = '\0';

	return buffer;
}