使用bitset和string的组合实现整数和ip地址的转换
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <bits/stdc++.h>
using namespace std;
int main() {
string s;
getline(cin, s);
for (char& c : s) {
if (c == '.') c = ' ';
}
istringstream strm(s);
string str;
unsigned k;
for (int i = 0; i < 4; ++i) {
strm >> k;
str += bitset<8>(k).to_string();
}
k = bitset<32>(str).to_ulong();
cout << k << endl;
cin >> k;
str = bitset<32>(k).to_string();
for (int i = 0; i < 4; ++i) {
cout << bitset<8>(str.substr(8 * i, 8)).to_ulong();
if (i != 3) cout << ".";
}
cout << endl;
}
查看1道真题和解析