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