aboutsummaryrefslogtreecommitdiff
path: root/lib/libk/string/itoa.c
blob: 09973454d484e72147d1e7ad84e9c3ade42788fa (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, unsigned base)
{
  p += 3 * sizeof(unsigned);
  *--p = '\0';

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

  return p;
}

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

  p = utoa(p, (unsigned)x, base);

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