itoa()和atoi()/atol()的源码(转…

来源:互联网 发布:海岛奇兵攻略软件 编辑:程序博客网 时间:2024/06/03 07:17
  1. #include 
  2. #include 
  3. #include 
  4. long __cdecl atol(
  5. const char *nptr
  6. )
  7. {
  8. int c; 
  9. long total; 
  10. int sign; 
  11. while isspace((int)(unsigned char)*nptr) )
  12. ++nptr;
  13. (int)(unsigned char)*nptr++;
  14. sign c; 
  15. if (c == ''-'' || == ''+'')
  16. (int)(unsigned char)*nptr++; 
  17. total 0;
  18. while (isdigit(c)) {
  19. total 10 total (c ''0''); 
  20. (int)(unsigned char)*nptr++; 
  21. }
  22. if (sign == ''-'')
  23. return -total;
  24. else
  25. return total; 
  26. }
  27. int __cdecl atoi(
  28. const char *nptr
  29. )
  30. {
  31. return (int)atol(nptr);
  32. }
  33. #ifndef _NO_INT64
  34. __int64 __cdecl _atoi64(
  35. const char *nptr
  36. )
  37. {
  38. int c; 
  39. __int64 total; 
  40. int sign; 
  41. while isspace((int)(unsigned char)*nptr) )
  42. ++nptr;
  43. (int)(unsigned char)*nptr++;
  44. sign c; 
  45. if (c == ''-'' || == ''+'')
  46. (int)(unsigned char)*nptr++; 
  47. total 0;
  48. while (isdigit(c)) {
  49. total 10 total (c ''0''); 
  50. (int)(unsigned char)*nptr++; 
  51. }
  52. if (sign == ''-'')
  53. return -total;
  54. else
  55. return total; 
  56. }
  57. #endif 
  58. #include 
  59. #include 
  60. #include 
  61. char_itoa(int value, charstring, int radix)
  62. {
  63. char tmp[33];
  64. chartp tmp;
  65. int i;
  66. unsigned v;
  67. int sign;
  68. charsp;
  69. if (radix 36 || radix <= 1)
  70. {
  71. __set_errno(EDOM);
  72. return 0;
  73. }
  74. sign (radix == 10 && value 0);
  75. if (sign)
  76. -value;
  77. else
  78. (unsigned)value;
  79. while (v || tp == tmp)
  80. {
  81. radix;
  82. radix;
  83. if (i 10)
  84. *tp++ i+''0'';
  85. else
  86. *tp++ ''a'' 10;
  87. }
  88. if (string == 0)
  89. string (char*)malloc((tp-tmp)+sign+1);
  90. sp string;
  91. if (sign)
  92. *sp++ ''-'';
  93. while (tp tmp)
  94. *sp++ *--tp;
  95. *sp 0;
  96. return string;
  97. }
  98. PS1: atoi()可以用二维数组的索引来实现,避免*10的循环。
  99. PS2: itoa()采用返回堆指针的方式得到结果,不会造成memory leak和指针问题。但是不可以通过传入的char*string返回结果,会造成指针问题。(可以改写为char**string,因此微软的sdk中实现的方式有问题)
  100. 注:源码可在VC目录下找到
原创粉丝点击