#include <iostream>
#include <assert.h>
/*
* @brief 求N的指数
* @param matter in 底数
* @param exponent in 指数
*/
int pow(const int matter, const int exponent);
/*
* @brief 字符串转整形
* @param strVal in 字符串
* @param val out 返回值
*/
void str_to_int(const char* strVal, int& val);
/*
* @brief 将ip地址压缩到整形中
* @param strIP in 地址
* @param IP out 压缩后的IP值
*/
void str_to_ip(const char* strIP, unsigned int& IP);
int main(int argc, char* argv[])
{
const char* strIP = "192.168.1.1";
unsigned int ip = 0;
str_to_ip(strIP, ip);
std::cout << ip << std::endl;
return 0;
}
int pow(int matter, int exponent)
{
int tmp = 1;
for(int i = 0; i < exponent; ++i)
{
tmp *= matter;
}
return tmp;
}
void str_to_int(const char* strVal, int& val)
{
//求长度
const char *p = strVal;
int size = 0; //字符串长度
while(*p != '\0')
{
assert(*p >= '0' && *p <= '9'); //ip地址非法
*p++;
size++;
}
int sum = 0;
for(int i = size - 1; i >= 0; --i)
{
sum += (strVal[i] - '0') * pow(10, size - i - 1);
}
val = sum;
}
void str_to_ip(const char* strIP, unsigned int& IP)
{
char buf[4][4];
int nIP[4];
int nCount = 0;
int j = 0;
unsigned int result = 0;
while(*strIP != '\0')
{
if(*strIP == '.')
{
buf[nCount][j] = '\0';
str_to_int(buf[nCount], nIP[nCount]);
result = ((result << 8) | (nIP[nCount] & 0xff)); //讲IP放到一个int型中
*strIP++;
nCount++;
assert(nCount <= 3);
j = 0;
}
buf[nCount][j++] = *strIP++;
}
buf[nCount][j] = '\0';
str_to_int(buf[nCount], nIP[nCount]);
result = ((result << 8) | (nIP[nCount] & 0xff)); //讲IP放到一个int型中;
}