IP Address
Time Limit: 1000MS | Memory Limit: 30000K | |
Total Submissions: 18305 | Accepted: 10551 |
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:
27 26 25 24 23 22 21 20 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
#include <stdio.h>
int main()
{
int t , a,b,c,d , i;
char str[100] ;
scanf("%d", &t);
while(t--)
{
scanf("%s", str);
a = 0 ; b= 0 ; c = 0 ; d = 0 ;
for(i = 0 ; i <= 7 ; i++)
{
if(i == 0 && str[i] == '1')
a += 128 ;
else if(i == 1 && str[i] == '1')
a += 64 ;
else if(i == 2 && str[i] == '1')
a += 32 ;
else if(i == 3 && str[i] == '1')
a += 16 ;
else if(i == 4 && str[i] == '1')
a += 8 ;
else if(i == 5 && str[i] == '1')
a += 4 ;
else if(i == 6 && str[i] == '1')
a += 2 ;
else if(i == 7 && str[i] == '1')
a += 1 ;
}
for(i = 8 ; i <= 15 ; i++)
{
if(i == 8 && str[i] == '1')
b += 128 ;
else if(i == 9 && str[i] == '1')
b += 64 ;
else if(i == 10 && str[i] == '1')
b += 32 ;
else if(i == 11 && str[i] == '1')
b += 16 ;
else if(i == 12 && str[i] == '1')
b += 8 ;
else if(i == 13 && str[i] == '1')
b += 4 ;
else if(i == 14 && str[i] == '1')
b += 2 ;
else if(i == 15 && str[i] == '1')
b += 1 ;
}
for(i = 16 ; i <= 23 ; i++)
{
if(i == 16 && str[i] == '1')
c += 128 ;
else if(i == 17 && str[i] == '1')
c += 64 ;
else if(i == 18 && str[i] == '1')
c += 32 ;
else if(i == 19 && str[i] == '1')
c += 16 ;
else if(i == 20 && str[i] == '1')
c += 8 ;
else if(i == 21 && str[i] == '1')
c += 4 ;
else if(i == 22 && str[i] == '1')
c += 2 ;
else if(i == 23 && str[i] == '1')
c += 1 ;
}
for(i = 24 ; i <= 31 ; i++)
{
if(i == 24 && str[i] == '1')
d += 128 ;
else if(i == 25 && str[i] == '1')
d += 64 ;
else if(i == 26 && str[i] == '1')
d += 32 ;
else if(i == 27 && str[i] == '1')
d += 16 ;
else if(i == 28 && str[i] == '1')
d += 8 ;
else if(i == 29 && str[i] == '1')
d += 4 ;
else if(i == 30 && str[i] == '1')
d += 2 ;
else if(i == 31 && str[i] == '1')
d += 1 ;
}
printf("%d.%d.%d.%d\n",a,b,c,d);
}
return 0;
}
4 00000000000000000000000000000000 00000011100000001111111111111111 11001011100001001110010110000000 01010000000100000000000000000001
Sample Output
0.0.0.0 3.128.255.255 203.132.229.128 80.16.0.1
Source
México and Central America 2004