posts - 7,comments - 214,trackbacks - 0

/*
 * Name: IP Address
 * Funcion: To convert binary numbers to decimal numbers
 * Input: 00000011100000001111111111111111
 * Output: 3.128.255.255
 */

#include <stdio.h>

void main()
{
 char input[32];
 int output[4];
 int count = -1;

 for(int i = 0; i < 4; i++ )
  output[i] = 0;

 gets( input );

 for( i = 0; i < 32; i++ )
 {
  if( i % 8 == 0 )
   count++;

  if( input[i] == '1' )
  {
   switch( i % 8 )
   {
    case 0:
     output[count] += 128;
     break;
    case 1:
     output[count] += 64;
     break;
    case 2:
     output[count] += 32;
     break;
    case 3:
     output[count] += 16;
     break;
    case 4:
     output[count] += 8;
     break;
    case 5:
     output[count] += 4;
     break;
    case 6:
     output[count] += 2;
     break;
    case 7:
     output[count] += 1;
     break;
    default:
     break;
   }
  }
 }
 printf( "%d.%d.%d.%d\n", output[0], output[1], output[2], output[3] );
}

posted on 2007-03-04 10:05 周Q 阅读(4221) 评论(3)  编辑 收藏 引用

FeedBack:
# re: 将二进制IP地址转换成十进制(C语言程序实现)
2007-03-06 01:29 | 踏雪赤兔
不知这样会否简洁些?呵呵~
void ip(char* s){
for(int i=0; i<4; ++i){
int sum=0;
for(int j=0; j<8; ++j) sum=sum*2+s[i*8+j]-'0';
printf("%d%c",sum,i==3?'\n':'.');
}
}
  回复  更多评论
  
# re: 将二进制IP地址转换成十进制(C语言程序实现)
2007-03-06 11:06 | 周Q
@踏雪赤兔
简洁了许多,谢谢你!希望以后和你多多学习! :)  回复  更多评论
  
# re: 将二进制IP地址转换成十进制(C语言程序实现)
2007-10-04 01:34 | 陌生人
int count = -1;

这里应该还要加 int i;

for(int i = 0; i < 4; i++ )//这句好像应该这样写吧 for(i = 0 ;i<4;i++)  回复  更多评论
  

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理