题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <iostream>
#include <sstream>
using namespace std;
//IP地址类
class IPAddress {
private:
int a, b, c, d;
public:
//构造函数
IPAddress(const string s);
IPAddress(const unsigned long long int a);
//析构函数
~IPAddress();
//将IP地址转换成一个整数
unsigned long long int transform(void)const;
//将一个整数转换成IP地址
void transform(const unsigned long long int n);
//输出(<<运算符重载)
friend ostream& operator<<(ostream& cout, IPAddress ip);
};
IPAddress::IPAddress(const string s) {
//输入重定向到字符串s,从字符串流读取数据
istringstream iss(s);
char ch;
iss >> this->a;
iss >> ch;
if (ch != '.') {
cout << "输入格式有误!" << endl;
return;
}
iss >> this->b;
iss >> ch;
if (ch != '.') {
cout << "输入格式有误!" << endl;
return;
}
iss >> this->c;
iss >> ch;
if (ch != '.') {
cout << "输入格式有误!" << endl;
return;
}
iss >> this->d;
return;
}
IPAddress::IPAddress(const unsigned long long int a) {
//先初始化,再赋值
this->a = 0;
this->b = 0;
this->c = 0;
this->d = 0;
this->transform(a);
return;
}
IPAddress::~IPAddress() {
}
unsigned long long int IPAddress::transform(void) const {
//在二进制下正整数左移八位相当于乘以2的8次方,也就是256;
return this->d + 256 * this->c + 256 * 256 * this->b + 256 * 256 * 256 *
this->a;
}
void IPAddress::transform(const unsigned long long int n) {
//将右移8位用除以256代替,并记录每一次的余数
int m = n;
this->d = n % 256;
m = n / 256;
if (m <= 0)
return;
this->c = m % 256;
m = m / 256;
if (m <= 0)
return;
this->b = m % 256;
m = m / 256;
if (m <= 0)
return;
this->a = m % 256;
m = m / 256;
if (m > 0)
cout << "输入超出范围!" << endl;
return;
}
int main() {
//为避免数据溢出,用无符号长长整型代替整型
unsigned long long int b = 0;
string s;
while (cin >> s >> b) { // 注意 while 处理多个 case
IPAddress ip1(s), ip2(b);
cout << ip1.transform() << endl;
cout << ip2 << endl;
}
}
// 64 位输出请用 printf("%lld")
ostream& operator<<(ostream& cout, IPAddress ip) {
cout << ip.a << '.' << ip.b << '.' << ip.c << '.' << ip.d;
// TODO: 在此处插入 return 语句
return cout;
}

