teststrtol.c 1.6 KB

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