> 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_putnbr_base.md).

# ft\_putnbr\_base

**Objective:**

Create a function that displays a number in a specified base system. The base system is provided as a string of characters, and the function must handle negative numbers and invalid arguments.

***

**Turn-in Directory:**

`ex04/`

***

**Files to Turn In:**

`ft_putnbr_base.c`

***

**Allowed Functions:**

`write`

***

**Prototype:**

```c
void ft_putnbr_base(int nbr, char *base);
```

***

#### **Detailed Explanation**

The `ft_putnbr_base` function takes an integer `nbr` and a string `base` as input. It displays the number in the specified base system. The function handles:

* Negative numbers (by printing a `-` sign).
* Invalid base systems (e.g., empty base, base with duplicate characters, base containing `+` or `-`).

***

#### **Code Implementation**

```c
void ft_putchar(char c)
{
    write(1, &c, 1);  // Write the character 'c' to the standard output
}

int double_char(char *str)
{
    int i;
    int j;

    i = 0;
    while (*(str + i))  // Loop through each character in the string
    {
        j = i + 1;
        while (*(str + j))  // Compare the current character with the rest of the string
        {
            if (*(str + i) == *(str + j))  // If duplicate characters are found
                return (1);  // Return 1 (true)
            j++;
        }
        i++;
    }
    return (0);  // Return 0 (false) if no duplicates are found
}

int check_base(char *base)
{
    int s_value;

    s_value = 0;
    while (base[s_value] != '\0')  // Loop through the base string
    {
        if (base[s_value] == '+' || base[s_value] == '-')  // Check for invalid characters
            return (1);  // Return 1 (invalid base)
        s_value++;
    }
    if (!base || base[0] == '\0' || base[1] == '\0')  // Check for empty or single-character base
        return (1);  // Return 1 (invalid base)
    if (double_char(base))  // Check for duplicate characters
        return (1);  // Return 1 (invalid base)
    return (s_value);  // Return the length of the base (valid base)
}

void ft_putnbr_base(int nbr, char *base)
{
    int s_value;
    long n;

    s_value = check_base(base);  // Check if the base is valid
    n = nbr;
    if (s_value == 1)  // If the base is invalid, return without printing
        return;
    if (n < 0)  // Handle negative numbers
    {
        ft_putchar('-');
        n = -n;
    }
    if (n >= s_value)  // Recursively print the number in the specified base
        ft_putnbr_base(n / s_value, base);
    ft_putchar(base[n % s_value]);  // Print the current digit
}
```

***

#### **Example Usage**

```c
#include <unistd.h>

void ft_putnbr_base(int nbr, char *base);

int main(void)
{
    ft_putnbr_base(42, "0123456789");  // Output: 42 (decimal)
    ft_putnbr_base(-42, "01");  // Output: -101010 (binary)
    ft_putnbr_base(255, "0123456789ABCDEF");  // Output: FF (hexadecimal)
    ft_putnbr_base(123, "poneyvif");  // Output: of (custom base)
    ft_putnbr_base(123, "");  // Output: (nothing, invalid base)
    ft_putnbr_base(123, "1");  // Output: (nothing, invalid base)
    ft_putnbr_base(123, "112");  // Output: (nothing, invalid base)
    return 0;
}
```

***

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

1. **Valid Bases**:
   * `"0123456789"` → Decimal base.
   * `"01"` → Binary 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**:
   * `-42` → Prints `-101010` in binary.
4. **Zero**:
   * `0` → Prints `0` in any valid base.

***

#### **Limitations of ft\_putnbr\_base**

1. **No Overflow Handling**:
   * The function does not handle integer overflow or underflow. If the number is too large or too small to fit in an `int`, the result is undefined.
2. **No Validation of Non-Numeric Characters**:
   * If the base contains invalid characters (e.g., `+`, `-`), the function will not print anything.

***

#### **How It Works**

1. **Helper Function: `ft_putchar`**:
   * This function takes a single character `c` and writes it to the standard output using the `write` system call.
2. **Helper Function: `double_char`**:
   * This function checks if the base string contains duplicate characters. If duplicates are found, it returns `1` (invalid base).
3. **Helper Function: `check_base`**:
   * This function validates the base string. It checks for:
     * Invalid characters (`+`, `-`).
     * Empty or single-character base.
     * Duplicate characters.
   * If the base is valid, it returns the length of the base string. Otherwise, it returns `1` (invalid base).
4. **Main Function: `ft_putnbr_base`**:
   * The function first checks if the base is valid using `check_base`. If the base is invalid, it returns without printing.
   * It handles negative numbers by printing a `-` sign and converting the number to positive.
   * It recursively prints the number in the specified base by dividing the number by the base length and printing the remainder.

***

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

1. **Base Validation**:
   * The function ensures the base is valid before processing the number. This includes checking for duplicate characters and invalid symbols.
2. **Recursion**:
   * Recursion is used to break down the number into digits in the specified base. This simplifies the logic for printing multi-digit numbers.
3. **Negative Numbers**:
   * The function handles negative numbers by printing a `-` sign and converting the number to positive.

<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_putnbr_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.
