字符串-06. IP地址转换


 1 /*
 2  * Main.c
 3  * D6-字符串-06. IP地址转换
 4  *  Created on: 2014年8月19日
 5  *******测试通过********
 6  *转载:http://blog.csdn.net/junjieguo/article/details/7392539
 7  */
 8 
 9 
10 #include <stdio.h>
11 
12 int bin_dec(int x, int n)  //自定义函数将二进制数转换为10进制
13 {
14     if(n == 0)
15     {
16         return 1;
17     }
18     return x * bin_dec(x, n-1);   //递归调用bin_dec()函数
19 }
20 
21 int main(void)
22 {
23     int i;
24     int ip[4] = {0};
25     char a[33];
26     //printf("请输入二进制数: 
");
27     scanf("%s", a);
28     for(i=0; i<8; i++)
29     {
30         if(a[i] == '1')
31         {
32             ip[0] += bin_dec(2, 7-i);
33         }
34     }
35     for(i=8; i<16; i++)
36     {
37         if(a[i] == '1')
38         {
39             ip[1] += bin_dec(2, 15-i);
40         }
41     }
42     for(i=16; i<24; i++)
43     {
44         if(a[i] == '1')
45         {
46             ip[2] += bin_dec(2, 23-i);
47         }
48     }
49     for(i=24; i<32; i++)
50     {
51         if(a[i] == '1')
52         {
53             ip[3] += bin_dec(2, 31-i);
54         }
55         if(a[i] == '')
56         {
57             break;
58         }
59     }
60     //printf("IP:
");
61     printf("%d.%d.%d.%d
", ip[0], ip[1], ip[2], ip[3]);//输出IP地址
62 
63     return 0;
64 }

题目链接:

http://pat.zju.edu.cn/contests/basic-programming/%E5%AD%97%E7%AC%A6%E4%B8%B2-06
转载:

http://blog.csdn.net/junjieguo/article/details/7392539

原文地址:https://www.cnblogs.com/boomkeeper/p/D6.html