原理:ip地址的每段可以看成是一个0-255的整数,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成
一个长整数。
举例:一个ip地址为10.0.3.193
每段数字 相对应的二进制数
10 00001010
0 00000000
3 00000011
193 11000001
组合起来即为:00001010 00000000 00000011 11000001,转换为10进制数就是:167773121,即该IP地址转换后的数字就是它了。
#include<iostream>
#include <string>
#include <sstream>
#include <vector>
#include<algorithm>
using namespace std;
bool IsChar(char ch)
{
if((ch>='A' && ch <='Z') || (ch >='a' && ch <= 'z'))
return true;
return false;
}
void wordInverted(char* pStr,char * pResurt)
{
if(pStr == NULL || pResurt == NULL)
{
return;
}
int len = strlen(pStr);
vector<string> allWord;
string temp;
for(int i = 0; i < len; i++)
{
if(IsChar(pStr[i]))
{
temp += pStr[i];
}
else
{
if(temp.length() > 0)
{
allWord.push_back(temp);
temp.clear();
}
}
}
if(temp.length() > 0)
{
allWord.push_back(temp);
temp.clear();
}
string strFinal;
for(int i=allWord.size()-1;i>=0;i--)
{
if(strFinal.length() > 0)
{
strFinal += ' ';
}
strFinal += allWord[i];
}
char * pTmp = (char*)strFinal.c_str();
int num = strlen(pTmp);
strcpy_s(pResurt,num+1,pTmp);
}
void ipStringToInt(char* pString,char* pInt)
{
if(pString == NULL || pInt == NULL)
return;
vector<string> ipChar;
string oneFild;
int ipLen = strlen(pString);
for(int i = 0; i < ipLen; i++)
{
if(pString[i] == '.')
{
ipChar.push_back(oneFild);
oneFild.clear();
continue;
}
oneFild += pString[i];
}
ipChar.push_back(oneFild);
if(ipChar.size() != 4)
return;
char* ip1 = (char*)ipChar[0].c_str();
char* ip2 = (char*)ipChar[1].c_str();
char* ip3 = (char*)ipChar[2].c_str();
char* ip4 = (char*)ipChar[3].c_str();
unsigned int value1 = atoi(ip1);
unsigned int value2 = atoi(ip2);
unsigned int value3 = atoi(ip3);
unsigned int value4 = atoi(ip4);
unsigned int sum = (value1 << 24) | (value2 << 16) | (value3 << 8) | value4;
char tmp[18];
sprintf_s(tmp,sizeof(tmp),"%u\0",sum);
strcpy_s(pInt,strlen(tmp)+1,tmp);
}
int main()
{
/*char* pWord = " I am a student ";
char presult[100];
wordInverted(pWord,presult);
cout<<presult<<endl;*/
char* pString = "10.0.3.193";
char pResu[10];
ipStringToInt(pString,pResu);
cout<<"10.0.3.193->"<<pResu<<endl;
return 0;
}