aboutsummaryrefslogtreecommitdiff
path: root/functions_reference/ref_ft_atoi_base.c
blob: 638b61d0a0714667003ed847e55b0e28ba8e3b17 (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
46
47
48
49
50
51
52
53
54
55
56
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ref_ft_atoi_base.c                                 :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/08 03:20:16 by cacharle          #+#    #+#             */
/*   Updated: 2020/11/07 17:17:01 by charles          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

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