atol(atoi)函数的实现要点

来源:互联网 发布:大闹天宫玉玺4进5数据 编辑:程序博客网 时间:2024/05/21 18:34
以下是c标准库中该函数的实现代码,从中分析要点
  1. /*** 
  2. *atox.c - atoi and atol conversion 
  3. * 
  4. * Copyright (c) 1989-1997, Microsoft Corporation. All rights reserved. 
  5. * 
  6. *Purpose: 
  7. * Converts a character string into an int or long. 
  8. * 
  9. *******************************************************************************/  
  10.   
  11. /*** 
  12. *long atol(char *nptr) - Convert string to long 
  13. * 
  14. *Purpose: 
  15. * Converts ASCII string pointed to by nptr to binary. 
  16. * Overflow is not detected. 
  17. * 
  18. *Entry: 
  19. * nptr = ptr to string to convert 
  20. * 
  21. *Exit: 
  22. * return long int value of the string 
  23. * 
  24. *Exceptions: 
  25. * None - overflow is not detected. 
  26. * 
  27. *******************************************************************************/  
  28.   
  29. long __cdecl atol(  
  30.                   const char *nptr  
  31.                   )  //1.const修饰
  32. {  
  33.     int c;          /* current char */  
  34.     long total;     /* current total */  
  35.     int sign;       /* if ''-'', then negative, otherwise positive */  
  36.   
  37.     /* skip whitespace */ 
  38. //char ,signed char 、unsigned char 类型的数据具有相同的特性然而当你把一个单字节的数赋给一个整型数时,便会看到它们在符号扩展上的差异。
  39. //ascii码当赋给整形数时要转为unsigned char再转为int
  40.     while ( isspace((int)(unsigned char)*nptr) )  //2.去掉首部的空格
  41.         ++nptr;  
  42.   
  43.     c = (int)(unsigned char)*nptr++;  //取得第一个非空格的字符
  44.     sign = c; /* save sign indication */  
  45.     if (c == '-' || c == '+')  //如果第一个非空格字符为符号
  46.         c = (int)(unsigned char)*nptr++; /* skip sign */  //跳过符号,将符号后的那个字符给c
  47.   
  48.     total = 0;  //结果置为0
  49.   
  50.     while (isdigit(c)) {  //3.如果碰到非法字符则停止
  51.         total = 10 * total + (c - '0'); /* accumulate digit */  
  52.         c = (int)(unsigned char)*nptr++; /* get next char */  
  53.     }  
  54.   
  55.     if (sign == '-')  
  56.         return -total;  
  57.     else  
  58.         return total; /* return result, negated if necessary */  


原创粉丝点击