libft
Loading...
Searching...
No Matches
ft_ltoa.c
Go to the documentation of this file.
1/* ************************************************************************** */
2/* */
3/* ::: :::::::: */
4/* ft_ltoa.c :+: :+: :+: */
5/* +:+ +:+ +:+ */
6/* By: tspoof <tspoof@student.hive.fi> +#+ +:+ +#+ */
7/* +#+#+#+#+#+ +#+ */
8/* Created: 2022/11/05 18:54:42 by tspoof #+# #+# */
9/* Updated: 2022/12/09 16:16:25 by tspoof ### ########.fr */
10/* */
11/* ************************************************************************** */
12
13#include "libft.h"
14
15static int ft_char_count(unsigned long n)
16{
17 int i;
18
19 i = 1;
20 while (n >= 10)
21 {
22 n = n / 10;
23 i++;
24 }
25 return (i);
26}
27
28static char *ft_ltostr(int sign, unsigned long len, unsigned long n, char *str)
29{
30 while (len)
31 {
32 str[len - 1] = (n % 10) + '0';
33 n = n / 10;
34 len--;
35 }
36 if (sign == -1)
37 str[0] = '-';
38 return (str);
39}
40
41char *ft_ltoa(long n)
42{
43 char *result;
44 int sign;
45 unsigned long num;
46 unsigned int len;
47
48 sign = 1;
49 len = 0;
50 if (n < 0)
51 {
52 sign = -1;
53 num = n * -1;
54 len++;
55 }
56 else
57 num = n;
58 len = len + ft_char_count(num);
59 result = (char *)ft_calloc(len + 1, sizeof(char));
60 if (!result)
61 return (NULL);
62 result = ft_ltostr(sign, len, num, result);
63 return (result);
64}
char * ft_ltoa(long n)
Long to ASCII.
Definition ft_ltoa.c:41
void * ft_calloc(size_t count, size_t size)
Allocate and zero.
Definition ft_calloc.c:15