minishell
ft_itoa.c
Go to the documentation of this file.
1 /* ************************************************************************** */
2 /* */
3 /* ::: :::::::: */
4 /* ft_itoa.c :+: :+: :+: */
5 /* +:+ +:+ +:+ */
6 /* By: kfujita <kfujita@student.42tokyo.jp> +#+ +:+ +#+ */
7 /* +#+#+#+#+#+ +#+ */
8 /* Created: 2022/04/18 06:34:36 by kfujita #+# #+# */
9 /* Updated: 2022/04/26 00:14:13 by kfujita ### ########.fr */
10 /* */
11 /* ************************************************************************** */
12 
13 #include "ft_string.h"
14 #include <stdlib.h>
15 
16 #define NUM_STR_BUF_LEN (12)
17 
18 static char *reverse_str(char *str)
19 {
20  char *str_top;
21  char *str_end;
22  char tmp;
23 
24  if (str == NULL)
25  return (NULL);
26  str_top = str;
27  str_end = str;
28  while (*str_end != '\0')
29  str_end++;
30  str_end -= 1;
31  while (str_top < str_end)
32  {
33  tmp = *str_end;
34  *str_end-- = *str_top;
35  *str_top++ = tmp;
36  }
37  return (str);
38 }
39 
40 static long ft_absl(long v)
41 {
42  if (v >= 0)
43  return (v);
44  else
45  return (v * -1);
46 }
47 
48 char *ft_itoa(int n)
49 {
50  char num_str_buf[NUM_STR_BUF_LEN];
51  int buf_pos;
52  long long_n;
53 
54  if (n == 0)
55  return (ft_strdup("0"));
56  buf_pos = 0;
57  long_n = ft_absl(n);
58  while (long_n != 0)
59  {
60  num_str_buf[buf_pos++] = (long_n % 10) + '0';
61  long_n /= 10;
62  }
63  if (n < 0)
64  num_str_buf[buf_pos++] = '-';
65  num_str_buf[buf_pos] = '\0';
66  return (reverse_str(ft_strdup(num_str_buf)));
67 }
static long ft_absl(long v)
Definition: ft_itoa.c:40
static char * reverse_str(char *str)
Definition: ft_itoa.c:18
#define NUM_STR_BUF_LEN
Definition: ft_itoa.c:16
char * ft_itoa(int n)
Definition: ft_itoa.c:48
char * ft_strdup(const char *s1)
Definition: ft_strdup.c:16