对于这道题,如果对进制转换、移位运算十分熟悉的话,做起来是十分简单的,而且很高效。如果不熟悉相关知识点,做起来费劲一些,下面的代码,对于输入IP地址转换为十进制数,采用的是比较原始的方法,代码显得冗杂;对于十进制数转换为IP地址,则使用的移位运算,代码简洁,而且运行高效。
#include <iostream>
#include <vector>
#include <string>
#include <bitset>
using namespace std;
int main()
{
string ip;
unsigned int value;
while (cin >> ip)
{
//*****输入IP地址处理*****//
vector<int> s1, s2, s3, s4;
int num[3] = {0};
int j = 0;
for (int i = 0; i < ip.length(); i++)
{
if (ip[i] == '.')
num[j++] = i;
}
for (int i = 0; i < ip.length(); i++)
{
if (i < num[0])
{
s1.push_back(ip[i]);
}
else if (i > num[0] && i < num[1])
{
s2.push_back(ip[i]);
}
else if (i > num[1] && i < num[2])
{
s3.push_back(ip[i]);
}
else if (i > num[2])
{
s4.push_back(ip[i]);
}
}
unsigned int number = 0;
for (int i = 0; i < s1.size(); i++)
{
number = number * 10 + (s1[i] - '0');
}
unsigned int number2 = 0;
for (int i = 0; i < s2.size(); i++)
{
number2 = number2 * 10 + (s2[i] - '0');
}
unsigned int number3 = 0;
for (int i = 0; i < s3.size(); i++)
{
number3 = number3 * 10 + (s3[i] - '0');
}
unsigned int number4 = 0;
for (int i = 0; i < s4.size(); i++)
{
number4 = number4 * 10 + (s4[i] - '0');
}
unsigned int s = 0;
s = (int)(s ^ number);
s = (int)(s << 8);
s = (int)(s ^ number2);
unsigned int w = 0;
w = (int)(w ^ number3);
w = (int)(w << 8);
w = (int)(w ^ number4);
unsigned int x = 0;
x = (int)(x ^ s);
x = (int)(x << 16);
x = (int)(x ^ w);
bitset<32> bit5(x); //bitset函数将对应数值转换为二进制数
unsigned int a = bit5.to_ullong(); //这里为unsigned long long
cout << a << endl;
//*****输入十进制型IP地址处理*****//
cin >> value;
int ip[4];
ip[0] = (value >> 24) & 255;
ip[1] = (value >> 16) & 255;
ip[2] = (value >> 8) & 255;
ip[3] = value & 255;
// printf("%d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
cout << ip[0] << '.' << ip[1] << '.' << ip[2] << '.' << ip[3] << endl;
}
return 0;
}
同时,附上运用进制转换、移位运算时的简洁代码。
#include<stdio.h>
int main() {
int a, b, c, d;
int ip[4];
unsigned int iip;
while(scanf("%d.%d.%d.%d",&a,&b,&c,&d)!=EOF){
scanf("%u", &iip);
unsigned int oip = (a << 24) + (b << 16) + (c << 8) + d;
printf("%u\n", oip);
ip[0] = (iip >> 24) & 255;
ip[1] = (iip >> 16) & 255;
ip[2] = (iip >> 8) & 255;
ip[3] = iip & 255;
printf("%d.%d.%d.%d\n", ip[0], ip[1], ip[2], ip[3]);
}
return 0;
}
但是这段代码的运行时间,要比,我第一次附上的代码,运行时间长很多。
此外,提交时,会发现printf函数比cout更加节省时间。
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
unsigned int a, b, c, d;
char ch;
while (cin >> a >> ch >> b >> ch >> c >> ch >> d)
{
cout << ((a << 24) | (b << 16) | (c << 8) | d) << endl;
cin >> a;
cout << ((a & 0xff000000) >> 24) << "." << ((a
&
0x00ff0000) >> 16) << "." << ((a & 0x0000ff00) >> 8) << "." << (a
& 0x000000ff) << endl;
}
}
附上述这段代码的目的是为了说明,可以采取简单的做法,对IP地址进行输入,cin在进行输入时,有空格或者其他字符时,就会默认为时新的输入,所以采取cin >> a >> ch >> b >> ch >> c >> ch >> d这种方式输入IP地址是可行的。
int ip[4];
ip[0] = (value >> 24) & 255;
ip[1] = (value >> 16) & 255;
ip[2] = (value >> 8) & 255;
ip[3] = value & 255;
关于上述这个代码段的移位运算,做一个一个说明: