ft_printf / src / utils / numbers.c 79 commits
30-04-2026
99 lines 2.0 kB
 1/* ************************************************************************** */
 2/*                                                                            */
 3/*                                                        :::      ::::::::   */
 4/*   numbers.c                                          :+:      :+:    :+:   */
 5/*                                                    +:+ +:+         +:+     */
 6/*   By: mleitao <mleitao@student.42.fr>            +#+  +:+       +#+        */
 7/*                                                +#+#+#+#+#+   +#+           */
 8/*   Created: 2026/03/15 14:49:46 by mleitao           #+#    #+#             */
 9/*   Updated: 2026/04/30 15:08:33 by mleitao          ###   ########.fr       */
10/*                                                                            */
11/* ************************************************************************** */
12
13#include "utils.h"
14
15static size_t	count_digits(long long n)
16{
17	size_t	count;
18
19	count = 0;
20	if (n <= 0)
21		count = 1;
22	while (n != 0)
23	{
24		n /= 10;
25		count++;
26	}
27	return (count);
28}
29
30static void	ltoa_convert(char *s, long long n, int len)
31{
32	if (n < 0)
33	{
34		*s = '-';
35		n = -n;
36	}
37	while (n > 0)
38	{
39		*(s + --len) = (n % 10) + '0';
40		n /= 10;
41	}
42}
43
44static size_t	get_len(unsigned long n, int base)
45{
46	size_t	len;
47
48	len = 1;
49	while (n >= (unsigned long)base)
50	{
51		n /= base;
52		len++;
53	}
54	return (len);
55}
56
57char	*ltoa(long n)
58{
59	long long	nb;
60	size_t		len;
61	char		*s;
62
63	nb = n;
64	len = count_digits(nb);
65	s = ft_calloc(len + 1, sizeof(char));
66	if (!s)
67		return (NULL);
68	if (!nb)
69	{
70		*s = '0';
71		return (s);
72	}
73	ltoa_convert(s, nb, len);
74	return (s);
75}
76
77char	*ultoa_base(unsigned long n, int base, int uppercase)
78{
79	char	*str;
80	char	*digits;
81	size_t	len;
82
83	if (base < 2 || base > 16)
84		return (NULL);
85	if (uppercase)
86		digits = "0123456789ABCDEF";
87	else
88		digits = "0123456789abcdef";
89	len = get_len(n, base);
90	str = ft_calloc(len + 1, sizeof(char));
91	if (!str)
92		return (NULL);
93	while (len--)
94	{
95		str[len] = digits[n % base];
96		n /= base;
97	}
98	return (str);
99}