atoi 实现

1887阅读 0评论2011-12-09 kgatheko
分类:C/C++


atoi 函数

   1. 代码可移植性
   2. 逻辑右移,算数右移
   3. 避免溢出
   4. 提高性能 (如:移位和加法运算的组合代替乘法)
      

  1. #define MAX_INT (~0U>>1)      

  2. int my_atoi(const char *str) {
  3.     int num=0;
  4.     int negative=0;
  5.     if(*str == '-' || *str == '+') {
  6.         if(*str == '-')
  7.             negative=1;
  8.         str++;
  9.     }
  10.     while(*str <= '9' && *str>='0') {
  11.         
  12.         num=((num<<3)+num+num)+(int)(*str-'0');
  13.         str++;
  14.     }
  15.     if(num >MAX_INT)
  16.         return MAX_INT;
  17.     if(negative)
  18.         num=~num+1;
  19.     return num;
  20. }
上一篇:char 类型指针 转化成 结构体A 指针
下一篇:最大公约数gcd