题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
/*
涉及到的知识点
1. 字符串处理
2. vector 数组的应用
3. 位运算 左移 右移 与运算 或运算
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
size_t ipToStr(string str){
vector<string> v;
int pos = str.find_first_of('.');
string tmp = str.substr(0, pos);
v.push_back(tmp);
str = str.substr(pos+1);
pos = str.find_first_of('.');
v.push_back(str.substr(0, pos));
str = str.substr(pos+1);
pos = str.find_first_of('.');
v.push_back(str.substr(0, pos));
str = str.substr(pos+1);
pos = str.find_first_of('.');
v.push_back(str.substr(0, pos));
size_t ipInt;
ipInt = stoi(v[0]);
ipInt = ipInt << 8;
ipInt = ipInt | stoi(v[1]);
ipInt = ipInt << 8;
ipInt = ipInt | stoi(v[2]);
ipInt = ipInt << 8;
ipInt = ipInt | stoi(v[3]);
return ipInt;
;
}
string numToIP(size_t str){
string ans;
size_t ipNum = (str);
size_t seg1, seg2, seg3, seg4;
seg4 = ipNum & 0xff;
ipNum = ipNum >> 8;
seg3 = ipNum & 0xff;
ipNum = ipNum >> 8;
seg2 = ipNum & 0xff;
ipNum = ipNum >> 8;
seg1 = ipNum & 0xff;
ans += to_string(seg1);
ans.append(1, '.');
ans += to_string(seg2);
ans.append(1, '.');
ans += to_string(seg3);
ans.append(1, '.');
ans += to_string(seg4);
return ans;
}
int main() {
string ip;
size_t num;
cin >> ip;
cin >> num;
cout << ipToStr(ip) << endl;
cout << numToIP(num) << endl;
return 0;
}
// 64 位输出请用 printf("%lld")

