File: utoa.c

package info (click to toggle)
picolibc 1.8.11-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 50,064 kB
  • sloc: ansic: 404,031; asm: 24,984; sh: 2,585; python: 2,289; perl: 680; pascal: 329; exp: 287; makefile: 222; cpp: 71; xml: 40
file content (69 lines) | stat: -rw-r--r-- 1,583 bytes parent folder | download
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
/* Copyright (c) 2014 Corinna Vinschen <corinna@vinschen.de> */
/*
FUNCTION
<<utoa>>---unsigned integer to string

INDEX
        utoa

SYNOPSIS
        #include <stdlib.h>
        char *utoa(unsigned <[value]>, char *<[str]>, int <[base]>);
        char *__utoa(unsigned <[value]>, char *<[str]>, int <[base]>);

DESCRIPTION
<<utoa>> converts the unsigned integer [<value>] to a null-terminated string
using the specified base, which must be between 2 and 36, inclusive.
<[str]> should be an array long enough to contain the converted
value, which in the worst case is sizeof(int)*8+1 bytes.

RETURNS
A pointer to the string, <[str]>, or NULL if <[base]> is invalid.

PORTABILITY
<<utoa>> is non-ANSI.

No supporting OS subroutine calls are required.
*/

#define _DEFAULT_SOURCE
#include <stdlib.h>

char *
__utoa(unsigned value, char *str, int base)
{
    const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
    int        i, j;
    unsigned   remainder;
    char       c;

    /* Check base is supported. */
    if ((base < 2) || (base > 36)) {
        str[0] = '\0';
        return NULL;
    }

    /* Convert to string. Digits are in reverse order.  */
    i = 0;
    do {
        remainder = value % base;
        str[i++] = digits[remainder];
        value = value / base;
    } while (value != 0);
    str[i] = '\0';

    /* Reverse string.  */
    for (j = 0, i--; j < i; j++, i--) {
        c = str[j];
        str[j] = str[i];
        str[i] = c;
    }

    return str;
}

char *
utoa(unsigned value, char *str, int base)
{
    return __utoa(value, str, base);
}