aboutsummaryrefslogtreecommitdiff
path: root/lib/string/itoa.c
blob: 2db9768e3dc0d2c2079eaf0aa94382d25c3595bd (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
#include <stdbool.h>
#include <string.h>

static const char *numbers = "0123456789abcdef";

char *
utoa(char *p, unsigned x, int base)
{
  p += 3 * sizeof(unsigned);
  *--p = '\0';

  do {
    *--p = numbers[x % base];
    x /= base;
  } while (x);

  return p;
}

char *
itoa(char *p, int x, int base)
{
  const bool is_negative = (x < 0);
  if (is_negative) x = -x;

  p = utoa(p, x, base);

  if (is_negative) *--p = '-';
  return p;
}