C++ 利用bitset
整数与IP地址间的转换
http://www.nowcoder.com/questionTerminal/66ca0e28f90c42a196afd78cc9c496ea
#include<iostream> #include<vector> #include<sstream> #include<bitset> using namespace std; long fun1(string s){ //IP地址转换十进制数 vector<int> v; istringstream in(s); int num; while(in>>num){ if(num>=0&&num<=255) v.push_back(num); else return -1; } string res=""; for(auto item:v){ bitset<8> temp(item); res+=temp.to_string(); } bitset<32> temp(res); long ip=temp.to_ulong(); return ip; } string fun2(long ip){ //将数字ip转换成字符串ip bitset<32> temp(ip); string s = temp.to_string(); vector<int> v; for(int i=0;i<4;++i) { bitset<8> temp2(s.substr(i*8,8)); v.push_back(temp2.to_ulong()); } string res=""; for(auto i:v) { if(i>=0&&i<=255) res = res+'.'+to_string(i); else return ""; } return res.substr(1); } int main(){ string s; long a; while(cin>>s>>a){ for(auto &c:s) { if(c=='.') c=' '; } long res1 = fun1(s); string res2 = fun2(a); if(res1!=-1) cout<<res1<<endl; if(res2!="") cout<<res2<<endl; } }