-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprint_helpers.c
More file actions
116 lines (96 loc) · 1.97 KB
/
print_helpers.c
File metadata and controls
116 lines (96 loc) · 1.97 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#include <string.h>
#include <unistd.h>
#include "main.h"
#include <stdlib.h>
/**
* alloc - Auxilliary Function
*
* Summary: Allocates memory, frees and returns NULL if failed
*
* @size: Size ot be allocated
*
* Return: (ptr) Success, (NULL) Failure
*/
void *alloc(size_t size)
{
void *ptr = malloc(size);
if (ptr == NULL)
return (NULL);
return (ptr);
}
/**
* int_to_string - Auxilliary Function
*
* Description: Converts and integer to a number string
*
* @num: Integer to be stringified
*
* Return: (num_str) char *
*/
char *int_to_string(long num)
{
long length = 1, tmp;
char *num_str;
long i;
tmp = num;
while (num)
{
length++;
num /= 10;
}
num_str = (char *) alloc(length * sizeof(char));
for (i = length - 2 ; i >= 0; --i)
{
num_str[i] = (tmp % 10) + '0';
tmp /= 10;
}
num_str[length - 1] = '\0';
return (num_str);
}
/**
* str_write - Auxilliary Function
*
* Summary: This function writes any string to standard output
*
* @number_string: String to be written to stdout
*
* Return: (count) int - Count of chars written
*/
int str_write(char *number_string)
{
size_t i, len, byte_size;
int count = 0;
if (number_string == NULL)
{
write(2, "Error", 6);
return (-1);
}
len = strlen(number_string);
byte_size = ((len - 1) / MAX_BYTE_SIZE) + 1;
for (i = 0; i < byte_size; ++i)
{
count += write(1, number_string + (i * MAX_BYTE_SIZE),
MIN(MAX_BYTE_SIZE, len - (i * MAX_BYTE_SIZE)));
}
return (count);
}
char *print_bin_helper(unsigned long num, char *buffer)
{
if (num == 0)
return (buffer);
*buffer = (num % 2) + '0';
num /= 2;
++buffer;
print_bin_helper(num, buffer);
return (buffer);
}
char *print_oct_helper(unsigned long num, char *buffer)
{
if (num == 0)
return (buffer);
*buffer = (num % 8) + '0';
num /= 8;
++buffer;
print_oct_helper(num, buffer);
return (buffer);
}