-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhex.c
83 lines (71 loc) · 1.13 KB
/
hex.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
#include "main.h"
/**
* hex - converts passed number to hexadecimal(lower case)
* @n: number to convert to hex
* Return: length of hexadecimal
*/
int hex(unsigned long int n)
{
long int len = 0, i;
long int *p;
unsigned long int temp;
if (n == 0)
return (_putchar('0'));
temp = n;
while (temp > 0)
{
temp /= 16;
len++;
}
p = malloc(sizeof(long int) * len);
if (!p)
return (-1);
for (i = 0; i < len; i++)
{
p[i] = n % 16;
n /= 16;
}
for (i = len - 1; i >= 0; i--)
{
if (p[i] > 9)
p[i] += 39;
_putchar(p[i] + '0');
}
free(p);
return (len);
}
/**
* HEX - converts passed number to hexadecimal(upper case)
* @n: number to convert to hex
* Return: length of hexadecimal
*/
int HEX(unsigned long int n)
{
long int len = 0, i;
long int *p;
unsigned long int temp;
if (n == 0)
return (_putchar('0'));
temp = n;
while (temp > 0)
{
temp /= 16;
len++;
}
p = malloc(sizeof(long int) * len);
if (!p)
return (-1);
for (i = 0; i < len; i++)
{
p[i] = n % 16;
n /= 16;
}
for (i = len - 1; i >= 0; i--)
{
if (p[i] > 9)
p[i] += 7;
_putchar(p[i] + '0');
}
free(p);
return (len);
}