> For the complete documentation index, see [llms.txt](https://42-guide.gitbook.io/42-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://42-guide.gitbook.io/42-guide/piscine-life/c04/ft_atoi_base.md).

# ft\_atoi\_base

**Objective:**

Create a function that converts the initial portion of a string pointed to by `str` to its integer representation. The string is in a specific base provided as a second parameter. The function should handle:

* Leading whitespace.
* An arbitrary number of `+` and `-` signs.
* Numeric characters in the specified base.

***

**Turn-in Directory:**

`ex05/`

***

**Files to Turn In:**

`ft_atoi_base.c`

***

**Allowed Functions:**

None

***

**Prototype:**

```c
int ft_atoi_base(char *str, char *base);
```

***

#### **Code Implementation**

```c
int	ft_strlen(char *str)
{
	int	i;

	i = 0;
	while (str[i])
		i++;
	return (i);
}

int	is_space(char c)
{
	return (c == ' ' || (c >= 9 && c <= 13));
}

int	is_valid_base(char *base)
{
	int	i;
	int	j;

	if (ft_strlen(base) < 2)  // Base must have at least 2 characters
		return (0);
	i = 0;
	while (base[i])
	{
		if (base[i] == '+' || base[i] == '-' || is_space(base[i]))  // Check for invalid characters
			return (0);
		j = i + 1;
		while (base[j])  // Check for duplicate characters
		{
			if (base[i] == base[j])
				return (0);
			j++;
		}
		i++;
	}
	return (1);  // Base is valid
}

int	get_value(char c, char *base)
{
	int	i;

	i = 0;
	while (base[i])
	{
		if (c == base[i])
			return (i);  // Return the index of the character in the base
		i++;
	}
	return (-1);  // Character not found in the base
}

int	ft_atoi_base(char *str, char *base)
{
	int	sign;
	int	result;
	int	base_len;
	int	value;

	if (!is_valid_base(base))  // Check if the base is valid
		return (0);
	sign = 1;
	result = 0;
	base_len = ft_strlen(base);
	while (is_space(*str))  // Skip leading whitespace
		str++;
	while (*str == '+' || *str == '-')  // Handle signs
	{
		if (*str == '-')
			sign *= -1;
		str++;
	}
	while ((value = get_value(*str, base)) >= 0)  // Convert characters to integer
	{
		result = result * base_len + value;
		str++;
	}
	return (result * sign);  // Apply the sign
}
```

***

#### **Example Usage**

```c
#include <stdio.h>

int ft_atoi_base(char *str, char *base);

int main(void)
{
    printf("Result 1: %d\n", ft_atoi_base("1010", "01"));  // Output: 10 (binary to decimal)
    printf("Result 2: %d\n", ft_atoi_base("  -FF", "0123456789ABCDEF"));  // Output: -255 (hex to decimal)
    printf("Result 3: %d\n", ft_atoi_base("++42", "0123456789"));  // Output: 42 (decimal)
    printf("Result 4: %d\n", ft_atoi_base("   --101", "01"));  // Output: 5 (binary to decimal)
    printf("Result 5: %d\n", ft_atoi_base("abc", "0123456789"));  // Output: 0 (invalid characters)
    printf("Result 6: %d\n", ft_atoi_base("123", ""));  // Output: 0 (invalid base)
    return 0;
}
```

***

#### **Edge Cases to Consider**

1. **Valid Bases**:
   * `"01"` → Binary base.
   * `"0123456789"` → Decimal base.
   * `"0123456789ABCDEF"` → Hexadecimal base.
   * `"poneyvif"` → Custom base.
2. **Invalid Bases**:
   * `""` → Empty base (invalid).
   * `"1"` → Single-character base (invalid).
   * `"112"` → Base with duplicate characters (invalid).
   * `"+-123"` → Base containing `+` or `-` (invalid).
3. **Negative Numbers**:
   * `"-1010"` in binary → Returns `-10`.
4. **Invalid Characters**:
   * `"abc"` in decimal → Returns `0` (invalid characters).
5. **Leading Whitespace**:
   * `" 42"` in decimal → Returns `42`.

***

#### **How It Works**

1. **Helper Function: `ft_strlen`**:
   * This function calculates the length of a string.
2. **Helper Function: `is_space`**:
   * This function checks if a character is a whitespace character.
3. **Helper Function: `is_valid_base`**:
   * This function validates the base string. It checks for:
     * Minimum length of 2.
     * Invalid characters (`+`, `-`, whitespace).
     * Duplicate characters.
4. **Helper Function: `get_value`**:
   * This function returns the index of a character in the base string. If the character is not found, it returns `-1`.
5. **Main Function: `ft_atoi_base`**:
   * The function first checks if the base is valid using `is_valid_base`. If the base is invalid, it returns `0`.
   * It skips leading whitespace and handles an arbitrary number of `+` and `-` signs.
   * It converts the string to an integer by interpreting it in the specified base.
   * It returns the final result, applying the sign.

***

#### **Key Points to Remember**

1. **Base Validation**:
   * The function ensures the base is valid before processing the string. This includes checking for invalid characters and duplicates.
2. **Sign Handling**:
   * The function processes multiple `+` and `-` signs and determines the final sign of the number.
3. **Character Conversion**:
   * The function converts characters to their corresponding values in the base system.
4. **Edge Cases**:
   * The function handles edge cases like invalid bases, invalid characters, and leading whitespace.

<br>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://42-guide.gitbook.io/42-guide/piscine-life/c04/ft_atoi_base.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
