summaryrefslogtreecommitdiff
path: root/src/libultra/libc/xlitob.c
blob: bbe263982e62690ae7022f06871019dd8cb8c602 (plain)
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
#include "PR/xstdio.h"
#include "string.h"
#include "stdlib.h"

#define BUFF_LEN 0x18

static char ldigs[] = "0123456789abcdef";
static char udigs[] = "0123456789ABCDEF";

void _Litob(_Pft* args, char type) {
    u8 buff[BUFF_LEN];
    const u8* numMap;
    s32 base;
    s32 idx;
    u64 num;
    lldiv_t quotrem;

    if (type == 'X') {
        numMap = udigs;
    } else {
        numMap = ldigs;
    }

    base = (type == 'o') ? 8 : ((type != 'x' && type != 'X') ? 10 : 16);
    idx = BUFF_LEN;
    num = args->v.ll;

    if ((type == 'd' || type == 'i') && args->v.ll < 0) {
        num = -num;
    }

    if ((num != 0) || (args->prec != 0)) {
        buff[--idx] = numMap[num % base];
    }

    args->v.ll = num / base;

    while ((args->v.ll > 0) && (idx > 0)) {
        quotrem = lldiv(args->v.ll, base);
        args->v.ll = quotrem.quot;
        buff[--idx] = numMap[quotrem.rem];
    }

    args->n1 = BUFF_LEN - idx;

    memcpy(args->s, buff + idx, args->n1);

    if (args->n1 < args->prec) {
        args->nz0 = args->prec - args->n1;
    }

    if ((args->prec < 0) && (args->flags & (FLAGS_ZERO | FLAGS_MINUS)) == FLAGS_ZERO) {
        idx = args->width - args->n0 - args->nz0 - args->n1;
        if (idx > 0) {
            args->nz0 += idx;
        }
    }
}