n进制转换为10进制

1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 /*******************************************************************************  
 5 函数名称: int n2dec(char *s, int length, int n) 
 6 描述: n进制转换为十进制  
 7 输入参数: 
 8     s:n进制数字符串
 9     length: 字符串s的长度      
10 返回: 转换后的十进制数
11 其他:字符串长度不要超过100   
12 *******************************************************************************/
13 unsigned int n2dec(char *s, int length, int n)
14 {
15     unsigned int res = 0;
16     int i = 0;
17     char a[100] = {0};
18     
19     for (i = 0; i < length; i++)
20     {
21         a[i] = s[i];
22         if (a[i] >= 'a' && a[i] <= 'z')
23         {
24             a[i] -= 32;
25         }
26         if (a[i] - '0' >= n && a[i] < 'A' || a[i] - 'A' + 10 >= n)
27         {
28             printf("data error\n");
29             return -1;
30         }
31         if (a[i] >= '0' && a[i] <= '9')
32         {
33             a[i] -= '0';
34         }
35         else if (a[i] >= 'A' && a[i] <= 'A' + n - 10)
36         {
37             a[i] = a[i] - 'A' + 10;
38         }
39         
40         res = res * n + a[i];
41     }
42     
43     return res;    
44 }
45 
46 int main(int argc, char **argv)
47 {
48     char *s = "FFFF";
49     int n = n2dec(s, strlen(s), 16);
50     
51     printf("n = %d\n", n);
52     return 0;
53 }

结果:

n = 65535
请按任意键继续. . .