aboutsummaryrefslogtreecommitdiff
path: root/functions_reference/ref_ft_atoi_base.c
blob: d668254fc00c787c1505c584870c674ce8ce62f9 (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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <ctype.h>
#include "libasm_test.h"

static bool
valid_base(char *base)
{
	if (strlen(base) < 2)
		return false;
	while (*base)
	{
		if (isspace(*base) || *base == '+' || *base == '-')
			return false;
		for (int i = 1; base[i]; i++)
			if (base[i] == *base)
				return false;
		base++;
	}
	return true;
}

int
ref_ft_atoi_base(char *str, char *base)
{
	long int nb;
	int radix;
	bool is_negative;

	if (!valid_base(base))
		return 0;
	while (isspace(*str))
		str++;
	is_negative = false;
	while (*str == '+' || *str == '-')
		if (*str++ == '-')
			is_negative = !is_negative;
	radix = strlen(base);
	nb = 0;
	while (*str && strchr(base, *str) != NULL)
	{
		nb *= radix;
		nb += strchr(base, *str) - base;
		str++;
	}
	return is_negative ? -nb : nb;
}