lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame^] | 1 | |
| 2 | #include <stdlib.h> |
| 3 | #include <stdio.h> |
| 4 | |
| 5 | |
| 6 | const char *strings[]={ |
| 7 | /* some simple stuff */ |
| 8 | "0", "1", "10", |
| 9 | "100", "1000", "10000", "100000", "1000000", |
| 10 | "10000000", "100000000", "1000000000", |
| 11 | |
| 12 | /* negative */ |
| 13 | "-0", "-1", "-10", |
| 14 | "-100", "-1000", "-10000", "-100000", "-1000000", |
| 15 | "-10000000", "-100000000", "-1000000000", |
| 16 | |
| 17 | /* test base>10 */ |
| 18 | "a", "b", "f", "g", "z", |
| 19 | |
| 20 | /* test hex */ |
| 21 | "0x0", "0x1", "0xa", "0xf", "0x10", |
| 22 | |
| 23 | /* test octal */ |
| 24 | "00", "01", "07", "08", "0a", "010", |
| 25 | |
| 26 | /* other */ |
| 27 | "0x8000000", |
| 28 | |
| 29 | /* check overflow cases: (for 32 bit) */ |
| 30 | "2147483645", |
| 31 | "2147483646", |
| 32 | "2147483647", |
| 33 | "2147483648", |
| 34 | "2147483649", |
| 35 | "-2147483645", |
| 36 | "-2147483646", |
| 37 | "-2147483647", |
| 38 | "-2147483648", |
| 39 | "-2147483649", |
| 40 | "4294967293", |
| 41 | "4294967294", |
| 42 | "4294967295", |
| 43 | "4294967296", |
| 44 | "4294967297", |
| 45 | "-4294967293", |
| 46 | "-4294967294", |
| 47 | "-4294967295", |
| 48 | "-4294967296", |
| 49 | "-4294967297", |
| 50 | |
| 51 | /* bad input tests */ |
| 52 | "", |
| 53 | "00", |
| 54 | "0x", |
| 55 | "0x0", |
| 56 | "-", |
| 57 | "+", |
| 58 | " ", |
| 59 | " -", |
| 60 | " - 0", |
| 61 | }; |
| 62 | int n_tests=sizeof(strings)/sizeof(strings[0]); |
| 63 | |
| 64 | void do_test(int base); |
| 65 | void do_utest(int base); |
| 66 | |
| 67 | int main(int argc,char *argv[]) |
| 68 | { |
| 69 | do_test(0); |
| 70 | do_test(8); |
| 71 | do_test(10); |
| 72 | do_test(16); |
| 73 | do_test(36); |
| 74 | |
| 75 | do_utest(0); |
| 76 | do_utest(8); |
| 77 | do_utest(10); |
| 78 | do_utest(16); |
| 79 | do_utest(36); |
| 80 | |
| 81 | return 0; |
| 82 | } |
| 83 | |
| 84 | void do_test(int base) |
| 85 | { |
| 86 | int i; |
| 87 | long n; |
| 88 | char *endptr; |
| 89 | |
| 90 | for(i=0;i<n_tests;i++){ |
| 91 | n=strtol(strings[i],&endptr,base); |
| 92 | printf("strtol(\"%s\",%d) len=%lu res=%ld\n", |
| 93 | strings[i],base,(unsigned long)(endptr-strings[i]),n); |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | void do_utest(int base) |
| 98 | { |
| 99 | int i; |
| 100 | unsigned long n; |
| 101 | char *endptr; |
| 102 | |
| 103 | for(i=0;i<n_tests;i++){ |
| 104 | n=strtoul(strings[i],&endptr,base); |
| 105 | printf("strtoul(\"%s\",%d) len=%lu res=%lu\n", |
| 106 | strings[i],base,(unsigned long)(endptr-strings[i]),n); |
| 107 | } |
| 108 | } |
| 109 | |