---
title: "将IP字符串转化为一个32bit整数"
author: "microapple"
date: "2013-03-29T21:40:06Z"
tags: []
categories: ["编程语言"]
slug: "ip-32bit"
draft: false
lastmod: "2013-03-29T21:40:06Z"
id: 1839026
url: "https://microapple.iteye.com/blog/1839026"
---

1.use strtok()
	
```c++
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位运算

```c++
//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;;

		
}
```