#include <bits/stdc++.h>
using namespace std;
unsigned int IPToValueREGEX(const string& strIP) {
regex pattern("\\.");
vector<string> vec(
sregex_token_iterator(strIP.begin(), strIP.end(), pattern, -1),
sregex_token_iterator());
unsigned int nResult = (atoi(vec[0].c_str()) << 24) +
(atoi(vec[1].c_str()) << 16) +
(atoi(vec[2].c_str()) << 8) +
atoi(vec[3].c_str());
return nResult;
}
unsigned int IPToValue(const string& strIP) // IP转换为整数
{
// IP转化为数值
// 没有格式检查
// 返回值就是结果
int a[4];
string IP = strIP;
string strTemp;
size_t pos;
size_t i = 3;
do {
pos = IP.find(".");
// 因为没有split
if (pos != string::npos) {
strTemp = IP.substr(0, pos);
a[i] = atoi(strTemp.c_str()); // int atoi(const char *str);
i--;
IP.erase(0, pos + 1); // 从位置0开始删除pos+1个字符
} else {
strTemp = IP;
a[i] = atoi(strTemp.c_str());
break;
}
} while (1);
unsigned int nResult = (a[3] << 24) + (a[2] << 16) + (a[1] << 8) + a[0];
return nResult;
}
string ValueToIP(const int& nValue) // 整数转换为ip
{
// 数值转化为IP
// 没有格式检查
// 返回值就是结果
char strTemp[20];
sprintf(strTemp, "%d.%d.%d.%d",
(nValue & 0xff000000) >> 24, // 取192
(nValue & 0x00ff0000) >> 16, // 取168
(nValue & 0x0000ff00) >> 8, // 取1
(nValue & 0x000000ff)); // 取254
return string(strTemp);
}
int main() {
string strIP = "192.168.1.254";
cout << IPToValue(strIP) << endl;
cout << ValueToIP(3232236030) << endl;
cout << IPToValueREGEX(strIP) << endl;
return 0;
}
class Solution:
def IPtoNum(self, ip):
arr = ip.split('.')
bs = ''
for s in arr;
ts = "{:08b}".format(int(s))
bs += ts
return int (bs, 2)
#转换str输出
def IPtoNum(self, ip : str) -> str:
arr = ip.split('.')
bs = ''
for s in arr;
ts = "{:08b}".format(int(s))
bs += ts
return int (bs, 2)
参考:
IP地址转换为整数