aboutsummaryrefslogtreecommitdiff
path: root/lib/string/itoa.c
blob: 3708be2e96efd60902be6dd65dd2539c625029fd (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 *
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;
}

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;
}