Chinaunix首页 | 论坛 | 博客
  • 博客访问: 370700
  • 博文数量: 100
  • 博客积分: 2500
  • 博客等级: 大尉
  • 技术积分: 1209
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-15 21:24
文章分类

全部博文(100)

文章存档

2011年(100)

分类: C/C++

2011-04-16 18:15:09


  1. #include <stdio.h>

  2. void
  3. strreverse(char *begin, char *end)
  4. {
  5.         char aux;

  6.         while (end > begin) {
  7.                 aux = *end, *end-- = *begin, *begin++ = aux;
  8.         }
  9. }

  10. void
  11. myitoa(int value, char *str, int base)
  12. {
  13.         static char num[] = "0123456789abcedfghijklmnopqrstuvwxyz";
  14.         char *wstr = str;
  15.         int sign;

  16.         if (base < 2 || base > 35) {
  17.                 *wstr = '\0';
  18.                 return ;
  19.         }

  20.         if ((sign = value) < 0)
  21.                 value = -value;

  22.         do {
  23.                 *wstr++ = num[value%base];
  24.         } while (value /= base);

  25.         if (sign < 0)
  26.                 *wstr++ = '-';

  27.         *wstr = '\0';

  28.         strreverse(str, wstr-1);
  29. }

  30. void
  31. myitoa2(int value, char *str, int base)
  32. {
  33.         char *wstr = str;
  34.         int sign;

  35.         if (base < 2 || base > 35) {
  36.                 *wstr = '\0';
  37.                 return ;
  38.         }

  39.         if ((sign = value) < 0)
  40.                 value = -value;

  41.         while (value) {
  42.                 *wstr++ = value % base + '0';
  43.                 value /= base;
  44.         }

  45.         if (sign < 0)
  46.                 *wstr++ = '-';

  47.         *wstr = '\0';

  48.         strreverse(str, wstr-1);
  49. }

  50. int
  51. main(void)
  52. {
  53.         int i = 13570;
  54.         char res[6] = {0};

  55.         myitoa(i, res, 10);
  56.         printf("Result: %s\n", res);

  57.         myitoa2(i, res, 10);
  58.         printf("Result: %s\n", res);

  59.         return (0);
  60. }



阅读(758) | 评论(1) | 转发(0) |
0

上一篇:没有了

下一篇:字符串2整数

给主人留下些什么吧!~~

onezeroone2011-04-24 16:37:14

static char num[];
'0'