`
microapple
  • 浏览: 15859 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

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



2.shift by bit-computing位运算
//input a CONST IP String,return a 32-bit integer
#include "stdafx.h"
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
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<pEnd){//calculate the value divided by '.'
			tmp=tmp*10+(*pStart-'0');
			pStart++;
		}
		//shift for 24.16.8.0 of each segment
		result+=(tmp<<shift);
		shift-=8;
		if(*pEnd=='\0')
			break;
		pStart=pEnd+1;
		pEnd++;
	}
	return result;
}

int main()
{

	char*a="1.0.0.1";
	cout<<"IP:"<<endl;
	cout<<"int:"<<ipstr2int(a)<<endl;;

		
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics