-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathint_to_string.c
95 lines (84 loc) · 2.12 KB
/
int_to_string.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdlib.h>
char *get_int(int num);
unsigned int _abs(int);
int get_numbase_len(unsigned int num, unsigned int base);
void fill_numbase_buff(unsigned int num, unsigned int base,
char *buff, int buff_size);
/**
* get_int - gets a character pointer to new string containing int
* @num: number to convert to string
*
* Return: character pointer to newly created string. NULL if malloc fails.
*/
char *get_int(int num)
{
unsigned int temp;
int length = 0;
long num_l = 0;
char *ret;
temp = _abs(num);
length = get_numbase_len(temp, 10);
if (num < 0 || num_l < 0)
length++; /* negative sign */
ret = malloc(length + 1); /* create new string */
if (!ret)
return (NULL);
fill_numbase_buff(temp, 10, ret, length);
if (num < 0 || num_l < 0)
ret[0] = '-';
return (ret);
}
/**
* _abs - gets the absolute value of an integer
* @i: integer to get absolute value of
*
* Return: unsigned integer abs rep of i
*/
unsigned int _abs(int i)
{
if (i < 0)
return (-(unsigned int)i);
return ((unsigned int)i);
}
/**
* get_numbase_len - gets length of buffer needed for an unsigned int
* @num: number to get length needed for
* @base: base of number representation used by buffer
*
* Return: integer containing length of buffer needed (doesn't contain null bt)
*/
int get_numbase_len(unsigned int num, unsigned int base)
{
int len = 1; /* all numbers contain atleast one digit */
while (num > base - 1)
{
len++;
num /= base;
}
return (len);
}
/**
* fill_numbase_buff - fills buffer with correct numbers up to base 36
* @num: number to convert to string given base
* @base: base of number used in conversion, only works up to base 36
* @buff: buffer to fill with result of conversion
* @buff_size: size of buffer in bytes
*
* Return: always void.
*/
void fill_numbase_buff(unsigned int num, unsigned int base,
char *buff, int buff_size)
{
int rem, i = buff_size - 1;
buff[buff_size] = '\0';
while (i >= 0)
{
rem = num % base;
if (rem > 9) /* return lowercase ascii val representation */
buff[i] = rem + 87; /* 10 will be a, 11 = b, ... */
else
buff[i] = rem + '0';
num /= base;
i--;
}
}