File: numtostr.c

package info (click to toggle)
dq 20230101-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,020 kB
  • sloc: ansic: 8,269; makefile: 363; sh: 176; python: 82
file content (45 lines) | stat: -rw-r--r-- 922 bytes parent folder | download | duplicates (8)
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
/*
20130604
Jan Mojzis
Public domain.
*/

#include "numtostr.h"

/*
The 'numtostr(strbuf,n)' converts number 'n' into the 0-terminated string.
The caller must allocate at least NUMTOSTR_LEN bytes for 'strbuf'.
The 'numtostr' function is ready for 128-bit integer.
*/
char *numtostr(char *strbuf, long long n) {

    long long len = 0;
    unsigned long long n1, n2;
    static char staticbuf[NUMTOSTR_LEN];
    int flagsign = 0;

    if (!strbuf) strbuf = staticbuf; /* not thread-safe */

    if (n < 0) {
        n1 = n2 = -(unsigned long long)n;
        flagsign = 1;
    }
    else {
        n1 = n2 = (unsigned long long)n;
    }

    do {
        n1 /= 10; ++len;
    } while (n1);
    if (flagsign) ++len;
    strbuf += len;

    do {
        *--strbuf = '0' + (n2 % 10);
        n2 /= 10;
    } while (n2);
    if (flagsign) *--strbuf = '-';

    while (len < NUMTOSTR_LEN) strbuf[len++] = 0;
    return strbuf;
}