文章作者:姜南(Slyar) 文章来源:Slyar Home (www.slyar.com) 转载请注明,谢谢合作。
水题,不过蛮实用的。
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.
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
Slyar:恩,就是把二进制的IP转换成十进制,注意数据可能不等长,有的后面有空格,有的没有。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdio.h> #include <string.h> int value[8] = {128, 64, 32, 16, 8, 4, 2, 1}; int main() { int i, j, k, n; int ip; char bits[50]; scanf("%d", &n); getchar(); while (n--) { gets(bits); i = 0; /* 4段IP */ for (k = 1; k <= 4; k++) { j = ip = 0; /* 每段8位 */ while (j < 8) { if (bits[i] == '1') ip += value[j]; i++; j++; } printf("%d", ip); if (k != 4) printf("."); } printf("\n"); } //system("pause"); return 0; } |
转载请注明:Slyar Home » POJ 2105 IP Address C语言版