# IP地址的转换

1. 可以用乘法操作；

2. 可以用移位操作；

3. 可以使用联合体定义解决；

#include <iostream>
using namespace std;

#define COUNT 4

union IP
{
struct CH
{
unsigned char Nu[COUNT];
}CHA;
unsigned int A;
}IPpre;

int Convert(char *p1,char *p2);
unsigned int IPConvert(char *IP10)
{
if(!IP10) return -1;
char *p1 = IP10;
char *p2 = IP10;
unsigned char Number[COUNT];
int n = 0;
while(*p1 != '.' && *p1 != '\0')
{
while(*p2 != '.' && *p2 != '\0')
{
p2 ++;
}
Number[n++] = Convert(p1,p2);
if(*p2 == '.')
{
p2++;
}
p1 = p2;
}

unsigned int sum = 0;
for(int i = 0;i < COUNT;i++)
{
sum += Number[i];
if(i != COUNT - 1)
{
sum = sum << 8;
}
}
return sum;
}

unsigned int IPConvert1(char *IP10)
{
if(!IP10) return -1;
char *p1 = IP10;
char *p2 = IP10;

int n = 3;
while(*p1 != '.' && *p1 != '\0')
{
while(*p2 != '.' && *p2 != '\0')
{
p2 ++;
}
IPpre.CHA.Nu[n--] = Convert(p1,p2);
if(*p2 == '.')
{
p2++;
}
p1 = p2;
}

return IPpre.A;
}

int Convert(char *p1,char *p2)
{
int N = p2 - p1;
int result = 0;
int index = 1;
int factor = 0;
if(*p2 == '.')
{
p2--;
}
for(int i = 0;i < N;i++)
{
factor = *p2 - '0';
result += factor * index;
index *= 10;
p2--;
}
return result;
}

int main()
{
char *IP = "192.168.1.1";
cout<<IPConvert(IP)<<endl;
cout<<IPConvert1(IP)<<endl;
return 0;
}