(TOJ 4413)IP address

描述

    To give you an IP address, it may be dotted decimal IP address, it may be 32-bit binary IP address.
    Is now required to give you an IP address, if the IP address is in dotted decimal output is 32-bit binary IP address,On the contrary, the output dotted decimal IP address.for example,the dotted decimal IP address 192.168.0.1,192->11000000,168->10101000,0->00000000,1->00000001,and the result is11000000101010000000000000000001 。

输入

Multiple inputs, each input a string,the length of the string is less than 33;

输出

Outputrequirements of the subject, if you enter an IP address in dotted decimal, then the output32-bit binary IP addresses, and vice versa, then the outputdotted decimal IP address.

样例输入

192.168.0.1

样例输出

11000000101010000000000000000001
#include<stdio.h>
#include<math.h>
#include<string.h>
#include<ctype.h>

char s[100];
void translate(int n)  //将10进制转换为8位的二进制
{
	int a[10];
	int i,j;
	i=0;
	while(1)
	{
		a[i++]=n%2;
		if(n/2==0) break;
		n/=2;
	}
	i--;
	for(j=1; j<8-i; j++)
	{
		printf("0");
	}
	for(j=i; j>=0; j--)
	{
		printf("%d",a[j]);
	}
}

void decimalTobinary(char *s)
{
	int i,j,len,sum;
	sum=0; i=0;len=strlen(s);
	while(i<len)
	{
		if(s[i]!='.')
		{
			sum+=s[i]-'0';
			sum*=10;
		}
		if(s[i]=='.' || i==len-1)
		{
			translate(sum/10);
			sum=0;
		}
		i++;
	}
	printf("\n");
}

void binaryTodecimal(char *s)
{
	int sum,i,j;
	sum=0;
	for(i=0; i<=24; i+=8)
	{
		for(j=i; j<i+7; j++)
		{
			sum+=s[j]-'0';
			sum*=2;
		}
		sum+=s[j]-'0';
		printf("%d",sum);
		if(i!=24)  printf(".");
		sum=0;
	}
	printf("\n");
}

void solve()
{
	char *p;
	while(gets(s))
	{
		p=strchr(s,'.');
		if(p==NULL)
		{
			binaryTodecimal(s);
		}
		else
		{
			decimalTobinary(s);
		}
	}
}

int main()
{
	solve();
	return 0;
}


你可能感兴趣的:(add)