POJ NO.2105 IP Address
Description
Suppose you are reading byte streams from any device, representing IP addresses. Your task is to convert a 32 characters long sequence of '1s' and '0s' (bits) to a dotted decimal format. A dotted decimal format for an IP address is form by grouping 8 bits at a time and converting the binary representation to decimal representation. Any 8 bits is a valid part of an IP address. To convert binary numbers to decimal numbers remember that both are positional numerical systems, where the first 8 positions of the binary systems are:
2^7 2^6 2^5 2^4 2^3 2^2 2^1 2^0
128 64 32 16 8 4 2 1
Input
The input will have a number N (1<=N<=9) in its first line representing the number of streams to convert. N lines will follow.
Output
The output must have N lines with a doted decimal IP address. A dotted decimal IP address is formed by grouping 8 bit at the time and converting the binary representation to decimal representation.
Sample Input
4
00000000000000000000000000000000
00000011100000001111111111111111
11001011100001001110010110000000
01010000000100000000000000000001
Sample Output
0.0.0.0
3.128.255.255
203.132.229.128
80.16.0.1
-------------------------------------------------------------------------
大概的意思是把32位的二进制数转换成用小数点(.)隔开的十进制表示的IP地址。
解答一:每次读入8个字符后转换成十进制数。一行是32个字符,需要处理4次,中间还要添加3次小数点。
#include<stdio.h>
int main()
{
//freopen("input.txt","r",stdin);
int i,j,k;
int n;
scanf("%d\n",&n);
for(i=0;i<n;i++)
{
for(j=0;j<4;j++)
{
int d=128,t=0;
for(k=0;k<8;k++)
{
char c=getchar()%48;//c=1 or 0,查ASCII码可知
t+=d*c;
d/=2;
}
if(j<3)
printf("%d.",t);
else
printf("%d\n",t);
}
}
return 0;
}
解答二
:使用strtol函数,将字符数组直接转换成十进制。
#include<stdio.h>
#include<stdlib.h>
int main()
{
//freopen("input.txt","r",stdin);
int i,j;
int n;
scanf("%d\n",&n);
for(i=0;i<n;i++)
{
for(j=0;j<4;j++)
{
char str[9];
int t;
scanf("%8s",str);
t=strtol(str,0,2);
if(j<3)
printf("%d.",t);
else
printf("%d\n",t);
}
}
return 0;
}
扩展:将一个32位的无符号整型数变换成IP地址,比如
1988,表示成无符号整型为00000000 00000000 00000111 11000100,转换成IP:0.0.7.196
#include<stdio.h>
int main()
{
//freopen("input.txt","r",stdin);
int i,j;
unsigned int n,a,t;
scanf("%u\n",&n);
for(i=0;i<n;i++)
{
scanf("%u",&a);
for(j=0;j<4;j++)
{
t=(a&0xff000000)>>24;//将32位二进制从左到右每次取8位
a<<=8;
if(j<3)
printf("%u.",t);
else
printf("%u\n",t);
}
}
return 0;
}