ip地址与整数互换
作者:互联网
题目描述
(1)ip地址转换为十进制整数
例如,ip地址10.0.3.193,可以分成四段,每段分别是00001010 00000000 00000011 01100001,将这四段拼接成一个32位的整数变成167773121
(2)整数转为ip地址
将167773121还原成10.0.3.193
题目分析
(1)ip地址转换为十进制整数
将ip地址第一段10左移24位、第二段0左移16位、第三段3左移8位,第四段193保持不变,可得到四个32位的整数,然后将四个整数按位与即可
(2)整数转为ip地址
将整数与255按位与得到ip地址第四段,然后整数右移8位,依次类推......
代码
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
vector<unsigned> split(string& s) {
int n = s.size();
vector<unsigned> vec;
string temp = "";
for (int i = 0; i < n; ++i) {
if (s[i] != '.') temp += s[i];
else {
vec.push_back(stoi(temp));
temp = "";
}
}
vec.push_back(stoi(temp));
return vec;
}
unsigned ip2int() {
string str;
cin >> str;
vector<unsigned> vec = split(str);
int k = 24;
for (unsignedi = 0; i < vec.size(); ++i) {
vec[i] = vec[i] << k;
k -= 8;
}
int ans = 0;
for (unsigned i = 0; i < vec.size(); ++i) {
ans |= vec[i];
}
return ans;
}
string int2ip() {
int t;
cin >> t;
vector<string> s;
for (int i = 0; i < 4; ++i) {
s.push_back(to_string(t & 255));
t = t >> 8;
}
reverse(s.begin(), s.end());
string ans = "";
for (int i = 0; i < 4; ++i) {
ans += s[i];
if (i == 3) break;
ans += '.';
}
return ans;
}
int main() {
cout << ip2int() << endl;
cout << int2ip() << endl;
return 0;
}
标签:string,int,ip,整数,地址,vec,互换 来源: https://www.cnblogs.com/foghorn/p/15147130.html