题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <bits/stdc++.h>
using namespace std;
void process(string strIP, long decIP, long& _decIP, string& _strIP){
stringstream iss(strIP);
string sTmp = "";
vector<long> nums; //long
while(getline(iss, sTmp, '.')){
nums.push_back(atol(sTmp.c_str()));
}
_decIP = nums[0] << 24 | nums[1] << 16 | nums[2] << 8 | nums[3]; //位运算组装
_strIP += to_string((decIP >> 24) & 0xff); //取第一个八位二进制转换成字符 & 0xff
_strIP += ".";
_strIP += to_string((decIP >> 16) & 0xff);
_strIP += ".";
_strIP += to_string((decIP >> 8) & 0xff);
_strIP += ".";
_strIP += to_string(decIP & 0xff);
}
int main(){
string strIP = "";
long decIP = 0;
cin >> strIP;
cin >> decIP;
long _decIP = 0;
string _strIP = "";
process(strIP, decIP, _decIP, _strIP);
cout << _decIP << endl;
cout << _strIP <<endl;
return 0;
}
华为题库题解 文章被收录于专栏
牛客华为题库的题解