-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatoibase.c
More file actions
60 lines (48 loc) · 1.38 KB
/
atoibase.c
File metadata and controls
60 lines (48 loc) · 1.38 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
// Assignment name : ft_atoi_base
// Expected files : ft_atoi_base.c
// Allowed functions: None
// --------------------------------------------------------------------------------
// Write a function that converts the string argument str (base N <= 16)
// to an integer (base 10) and returns it.
// The characters recognized in the input are: 0123456789abcdef
// Those are, of course, to be trimmed according to the requested base. For
// example, base 4 recognizes "0123" and base 16 recognizes "0123456789abcdef".
// Uppercase letters must also be recognized: "12fdb3" is the same as "12FDB3".
// Minus signs ('-') are interpreted only if they are the first character of the
// string.
// Your function must be declared as follows:
// int ft_atoi_base(const char *str, int str_base);
#include <stdio.h>
int ft_strlen(char *str)
{
int i = 0;
while(str[i])
i++;
return(i);
}
int ft_atoi_base(const char *s, int str_base)
{
int sign = 1;
int res = 0;
int i = 0;
char *str;
str = (char *)s;
if(str[i++] == '-')
sign = -sign;
while(str[i])
{
if(str[i] >= '0' && str[i] <= '9')
res = res * str_base + (str[i] - '0');
if(str[i] >= 'A' && str[i] <= 'F')
res = res * str_base + (str[i] - 55);
if(str[i] >= 'a' && str[i] <= 'f')
res = res * str_base + (str[i] - 87);
i++;
}
return(sign * res);
}
int main()
{
char *res = "-1AD256F";
printf("%d", ft_atoi_base(res, 16));
}