File: numtostr.c

package info (click to toggle)
tinyssh 20250501-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,388 kB
  • sloc: ansic: 20,245; sh: 1,582; python: 1,449; makefile: 913
file content (45 lines) | stat: -rw-r--r-- 961 bytes parent folder | download | duplicates (2)
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
20241208 - reformated using clang-format
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;
}