题解 | 整数与IP地址间的转换
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <iostream> #include <bitset> #include <vector> #include <sstream> using namespace std; int main() { string ip_str; unsigned long ip_num; cin >> ip_str; cin >> ip_num; //ip->10进制 stringstream ss(ip_str); string token; unsigned long decimal = 0; while(getline(ss, token, '.')) { decimal = (decimal << 8) | stoi(token); } //10进制->ip bitset<32> bits(ip_num); string ans_str; for(int i = 3; i >= 0; --i) { unsigned long tmp = (bits.to_ulong() >> (i*8)) & 0xFF; ans_str = ans_str + to_string(tmp) + (i ? "." : ""); } cout << decimal << endl; cout << ans_str << endl; return 0; }