题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <bitset>
#include <iostream>
#include <bits/stdc++.h>
#include <istream>
#include <string>
using namespace std;
/* 将点分形式转化为二进制形式,再转化为十进制数*/
long long two2ten(const std::string& ip) {
std::istringstream iss(ip);
std::string tmp, all;
while(getline(iss, tmp, '.')) {
int decimal = stoi(tmp);
std::string binary = std::bitset<8>(decimal).to_string(); // bitset做十进制到二进制转换
all = all + binary;
}
long long result = std::stoll(all, nullptr, 2); // 使用 std::stoll 进行转换,stoi会越界
return result;
}
string ten2two(string& ip10) {
string binary = bitset<32>(stoll(ip10)).to_string(); // stoll,stoi会越界
string result;
for (int i = 0; i < binary.size(); i += 8) {
string tmp = binary.substr(i, 8);
// cout << "tmp = " << tmp << endl;
result += to_string(stoi(tmp, nullptr, 2));
if (i < 24) {
result += ".";
}
}
return result;
}
int main() {
string ip;
string ip10;
cin >> ip;
cin >> ip10;
cout << two2ten(ip) << endl;
cout << ten2two(ip10) << endl;
}
// 64 位输出请用 printf("%lld")
