将IP字符串转化为一个32bit整数

1.use strtok()
char a[]="1.0.0.1";
char *p=NULL;
char *d=".";
p=strtok(a,d);
while(p){
cout< p=strtok(NULL,d);
}



2.shift by bit-computing位运算
//input a CONST IP String,return a 32-bit integer
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;

int ipstr2int(const char*ip){
int result = 0;
int tmp = 0;
int shift = 24;
const char*pEnd = ip;
const char*pStart = ip;

while(*pEnd!='\0'){
while(*pEnd!='.'&&*pEnd!='\0'){//find out the "." in IP String
pEnd++;
}
tmp=0;
while(pStart tmp=tmp*10+(*pStart-'0');
pStart++;
}
//shift for 24.16.8.0 of each segment
result+=(tmp< shift-=8;
if(*pEnd=='\0')
break;
pStart=pEnd+1;
pEnd++;
}
return result;
}

int main()
{

char*a="1.0.0.1";
cout<<"IP:"< cout<<"int:"<

}

你可能感兴趣的:(将IP字符串转化为一个32bit整数)