《c程序设计语言》读书笔记-十六位进制数转十进制

#include <stdio.h>
#include <stdio.h>

int htoi(char s[]);

main()
{
     char s1[] = "10";
     char s2[] = "2D";
     char s3[] = "3f";
     char s4[] = "0X4F";
     char s5[] = "0x3a";

     printf("%s -> %d\n", s1, htoi(s1));
     printf("%s -> %d\n", s2, htoi(s2));
     printf("%s -> %d\n", s3, htoi(s3));
     printf("%s -> %d\n", s4, htoi(s4));
     printf("%s -> %d\n", s5, htoi(s5));
}
int htoi(char s[])
{
     int n = 0;
     int i = -1;

     while (s[++i] != '\0')
    {
          if (i == 0 && s[i] == '0')
               continue;
          else if (s[i] == 'x' || s[i] == 'X')
               continue;
          else if ('0'<= s[i] && s[i] <= '9')
               n = n * 16 + (s[i] - '0');
          else if ('a'<= s[i] && s[i] <= 'f')
               n = n * 16 + (s[i] - 'a' + 10);
          else if ('A' <= s[i] && s[i] <= 'F')
               n = n * 16 + (s[i] - 'A' + 10);
          else
               return -1;
     }
     return n;
}

程序转自:http://blog.csdn.net/dc_726/article/details/7032656


posted @ 2014-10-30 11:21  司空格子Ored  阅读(178)  评论(0编辑  收藏  举报