33#include <stdio.h>
44#include <limits.h>
55
6+ int my_atoi (char * num , int size , int base ) {
7+ int i , ret = 0 ;
8+ int neg = 0 ;
9+
10+ if (!num || size == 0 )
11+ return ret ;
12+
13+ // take care of negative sign if any
14+ if (num [0 ] == '-' ) {
15+ neg = 1 ;
16+ i = 1 ;
17+ } else {
18+ i = 0 ;
19+ }
20+
21+ // take care of different bases
22+ for (i ; i < size ; i ++ ) {
23+ ret *= base ;
24+ if (base != 16 )
25+ ret += num [i ] - '0' ;
26+ else { // special handling for Hex numbers
27+ if (num [i ] >= 'a' && num [i ] <= 'f' )
28+ ret += num [i ] - 'a' + 10 ;
29+ else if (num [i ] >= 'A' && num [i ] <= 'F' )
30+ ret += num [i ] - 'A' + 10 ;
31+ else if (num [i ] >= '0' && num [i ] <= '9' )
32+ ret += num [i ] - '0' ;
33+ }
34+ }
35+
36+ return neg ? - ret : ret ;
37+ }
638
739int main (int argc , char * * argv ) {
8- int i ;
9- char buffer [64 ];
10- int buf_s = 64 ;
11-
12- int test_base10 [6 ] = {0 , -10 , 12345 , -12345 , -32768 , INT_MAX };
13- memset (buffer , 0 , buf_s );
14- for (i = 0 ; i < 6 ; i ++ )
15- printf ("%s " , itoa (test_base10 [i ], buffer , 10 ));
40+ int ret ;
41+
42+ char * test_base10 = "123456" ;
43+ printf ("my: %d expect: %d" , my_atoi (test_base10 , strlen (test_base10 ), 10 ), atoi (test_base10 ));
1644 printf ("\n==============\n" );
1745
18- int test_base2 [6 ] = {0 , -16 , 12345 , -12345 , -32768 , INT_MAX };
19- memset (buffer , 0 , buf_s );
20- for (i = 0 ; i < 6 ; i ++ )
21- printf ("%s " , itoa (test_base2 [i ], buffer , 2 ));
22- printf ("\n==============\n" );
23-
24- int test_base16 [6 ] = {0 , -10 , 0x1234abcd , -12345 , -32768 , INT_MAX };
25- memset (buffer , 0 , buf_s );
26- for (i = 0 ; i < 6 ; i ++ )
27- printf ("%s " , itoa (test_base16 [i ], buffer , 16 ));
46+ test_base10 = "-123456" ;
47+ printf ("my: %d expect: %d " , my_atoi (test_base10 , strlen (test_base10 ), 10 ), atoi (test_base10 ));
2848 printf ("\n==============\n" );
49+
50+ char * test_base2 = "1000" ;
51+ printf ("%d " , my_atoi (test_base2 , strlen (test_base2 ), 2 ));
52+ printf ("\n==============\n" );
53+
54+ test_base2 = "111" ;
55+ printf ("%d " , my_atoi (test_base2 , strlen (test_base2 ), 2 ));
56+ printf ("\n==============\n" );
57+
58+ char * test_base16 = "1a" ;
59+ printf ("%d " , my_atoi (test_base16 , strlen (test_base16 ), 16 ));
60+ printf ("\n==============\n" );
61+
62+ test_base16 = "100" ;
63+ printf ("%d " , my_atoi (test_base16 , strlen (test_base16 ), 16 ));
64+ printf ("\n==============\n" );
65+
66+ test_base16 = "ff" ;
67+ printf ("%d " , my_atoi (test_base16 , strlen (test_base16 ), 16 ));
68+ printf ("\n==============\n" );
69+
70+ test_base16 = "1A" ;
71+ printf ("%d " , my_atoi (test_base16 , strlen (test_base16 ), 16 ));
72+ printf ("\n==============\n" );
73+
74+ test_base16 = "FF" ;
75+ printf ("%d " , my_atoi (test_base16 , strlen (test_base16 ), 16 ));
76+ printf ("\n==============\n" );
2977 return 0 ;
3078}
0 commit comments