Chinaunix首页 | 论坛 | 博客
  • 博客访问: 239493
  • 博文数量: 62
  • 博客积分: 973
  • 博客等级: 准尉
  • 技术积分: 530
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-16 23:25
文章分类

全部博文(62)

文章存档

2013年(1)

2012年(14)

2011年(47)

分类: C/C++

2011-11-20 22:27:51

  1. #include <stdio.h>

  2. // decimal to string
  3. void dec_itoa(int num, char *str)
  4. {
  5.     int i=0,j=0;
  6.     char temp[12];
  7.     int n = num<0 ? -num:num;
  8.     while(n)
  9.     {
  10.         temp[i++]=n%10+'0';
  11.         n /=10;
  12.     }
  13.     temp[i]='\0'; /* 如是负数,留着放符号 */
  14.     if(num>0) i--;
  15.     while(i>=0)
  16.         str[j++]=temp[i--];

  17.     if(num<0)
  18.         str[0]='-';
  19.     str[j]='\0';
  20. }

  21. // sting to decimal int
  22. int dec_atoi(const char *str)
  23. {
  24.     int x=0;
  25.     int i,sign=1;
  26.     while(*str==' ') str++;
  27.     if(str[0]=='+'||str[0]=='-')
  28.     {
  29.         sign= (*str=='-'?-1:1);
  30.     }
  31.     else if( isdigit(str[0]) )
  32.         x = str[0] - '0';
  33.     for(i = 1; str[i] != '\0'; ++i)
  34.     {
  35.         if(str[i]>='0' && str[i]<='9')
  36.             x=10*x + *str-'0';
  37.     }
  38.     return sign*x;
  39. }

  40. void main()
  41. {
  42.     char str[20];
  43.     int n;
  44.     printf("Please input an integer(-32767,32767):\n");
  45.     scanf("%d",&n);
  46.     dec_itoa(n,str);
  47.     printf("output string: %s\n",str);

  48.     printf("string to int: %d\n",dec_atoi(str));
  49. }

// 把八、十、十六进制字符串转化成整数:

  1. int StrToInt(char * str)
  2. {
  3.    int value = 0;
  4.    int sign = 1;
  5.    int radix;

  6.    if(*str == '-')
  7.    {
  8.       sign = -1;
  9.       str++;
  10.    }
  11.    if(*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
  12.    {
  13.       radix = 16;
  14.       str += 2;
  15.    }
  16.    else if(*str == '0') // 八进制首字符为0
  17.    {
  18.       radix = 8;
  19.       str++;
  20.    }
  21.    else
  22.       radix = 10;

  23.    while(*str)
  24.    {
  25.       if(radix == 16)
  26.       {
  27.         if(*str >= '0' && *str <= '9')
  28.            value = value * radix + *str - '0';
  29.         else
  30.            value = value * radix + (*str | 0x20) - 'a' + 10;
  31.        // 转化为小写字母
  32.       }
  33.       else
  34.         value = value * radix + *str - '0';
  35.       str++;
  36.    }
  37.    return sign*value;
  38. }
阅读(1261) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~