IP地址转换整型(算法练习)

// ipTrans.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>

typedef union
{
	unsigned char data[4];
	unsigned int ip;
}IP;

unsigned int TransIP(char *pstrIp)
{
	IP ipstr = {0};
	unsigned char temdata[3] = {0};
	int i = 0, k = 0, point = 0, t = 0;

	while(pstrIp[i] != '\0'){
		
		if(pstrIp[i] != '.')
		{ 			  		
			 if(point > 0)
			 {
				 ipstr.data[k++] = (temdata[0] - '0')*100 + (temdata[1] - '0')*10 +(temdata[2] - '0');
				 point = 0;
				 t = 0;
			 }
			 temdata[t++] = pstrIp[i];			
		}
		else
		{
			point++;
		}

		i++;
	}

	ipstr.data[k] = (temdata[0] - '0')*100 + (temdata[1] - '0')*10 +(temdata[2] - '0');
	return ipstr.ip;
}


int _tmain(int argc, _TCHAR* argv[])
{
	char *ipstr = "169.168.1.1";
	unsigned int ip = TransIP(ipstr);
	printf("%s转换为整数为%u", ipstr,ip);
	system("pause");
	return 0;
}

上面是在vs2010上编写的代码,运行结果如下

发布了27 篇原创文章 · 获赞 19 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/muaxi8/article/details/92660483