/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   ft_putnbr_base.c                                   :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: keanders <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2024/07/23 15:44:37 by keanders          #+#    #+#             */
/*   Updated: 2024/07/23 16:26:54 by keanders         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

/*

   This function accepts a decimal input integer, and
   a symbol set referred to as base.

   Invalid arguments, nothing should be displayed!
	Empty base
	Base contains the same symbola twice - 00 11 22 666 606 ...
	Base contains '+' or '-'.

This function must handle negative numbers.
*/

#include <unistd.h>

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

	i = 0;
	if (base[0] == '\0' || base[1] == '\0')
		return (0);
	while (base[i])
	{
		j = i + 1;
		while (base[j])
		{
			if (base[i] == base[j])
				return (0);
			j++;
		}
		if (base[i] == '+' || base[i] == '-')
			return (0);
		if (base[i] < 32 || base[i] > 126)
			return (0);
		i++;
	}
	return (1);
}

void	ft_putchar(char c)
{
	write(1, &c, 1);
}

//void op_engine(long safe_nb, int base_size, int nbr, char *base)
void op_engine(long safe_nb, int nbr, char *base)
{
    int i;
    int		nbr_str[500];
    int		base_size;
    
    base_size = 0;  
    if (safe_nb < 0)
		{
			safe_nb = -safe_nb;
			ft_putchar('-');
		}
		while (base[base_size])
			base_size++;
		while (safe_nb)
		{
			nbr_str[i] = safe_nb % base_size;
			safe_nb = safe_nb / base_size;
			i++;
		}
		while (i-- > 0)
			ft_putchar(base[nbr_str[i]]);
}
void	ft_putnbr_base(int nbr, char *base)
{
	long	safe_nb;
	int		nbr_str[500];

	safe_nb = nbr;
	if (legal_base_check(base))
	{
        op_engine(safe_nb, nbr, base);
	}
}

#include <stdio.h>

int main() {
    char my_base[] = "01";
    ft_putnbr_base(-10, my_base);
    printf("\n");
    printf("my_base %s : %d\n", my_base, legal_base_check(my_base));
    printf("\n");
    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: