IP地址格式输出

     本实例:输入一个32位二进制的数,每隔八位分开将其转换为十进制以IP格式输出。

    

    

 1 #include <stdio.h>
 2 /*
 3 以IP地址形式输出
 4 */
 5 int main(void)
 6 {
 7     int i;
 8     int ip[4]={0};
 9     char a[33];
10     printf("please input binary number:\n");
11     scanf("%s",a);//puts(a);
12     for(i=0;i<8;i++)
13     {
14      if(a[i]=='1')
15         {
16          ip[0]+=bin_dec(2,7-i);
17         }
18     }
19 
20     for(i=8;i<16;i++)
21     {
22      if(a[i]=='1')
23         {
24          ip[1]+=bin_dec(2,15-i);
25         }
26     }
27     for(i=16;i<24;i++)
28     {
29      if(a[i]=='1')
30         {
31          ip[2]+=bin_dec(2,23-i);
32         }
33     }
34     for(i=24;i<32;i++)
35     {
36      if(a[i]=='1')
37         {
38          ip[3]+=bin_dec(2,31-i);
39         }
40 
41     }
42     printf("ip:\n");
43     printf("%d.%d.%d.%d",ip[0],ip[1],ip[2],ip[3]);
44 
45     return 0;
46 }
47 //求2的n次
48 int bin_dec(int x,int n)
49 {
50 
51     if(n==0) return 1;
52     return x*bin_dec(x,n-1);
53 
54 }

       运行结果如图:

posted @ 2014-05-01 17:26  尾巴草  阅读(997)  评论(0编辑  收藏  举报