算法练习Ip地址与整数的互相转换ipstrToint


int ipstr2int(const char *ip, unsigned int *ipvalue)
{
	if (ip == NULL || ipvalue==NULL)
		return -1;

	unsigned int	result = 0;
	int	tmp = 0;
	int	shift = 24;
	const char *pEnd = ip;
	const char *pStart = ip;

	while(*pEnd != '\0')
	{
		//到地址符里的’.’
		while(*pEnd != '.' && *pEnd != '\0')
			pEnd++;
		tmp = 0;
		//计算每个’.’之间的数值
		while(pStart < pEnd)
		{
			tmp = tmp * 10 + (*pStart - '0');
		pStart++;
		}
		if(tmp<0 || tmp >255)
		{
			return -1;
		}
		//将计算好的数值分别左移24位,16位,8位,0位
		result += (tmp << shift);
		shift -= 8;
		if (*pEnd == '\0')
			break;
		pStart = pEnd + 1;
		pEnd++;
	}
	*ipvalue = result;
	return 1;
}


int ip2str(unsigned int ip, char *buf, size_t len)
{
	if(buf == NULL || len<16)
	{
		return -1;
	}
	size_t length = sizeof(ip);//32位ip地址的字节数
	unsigned char *p = (unsigned char *)&ip+sizeof(ip)-1;//指 向ip地址最高字节
	char *p1 = buf;
	while(length)
	{
		unsigned char tmp = *p;
		char *pstart= p1;

		do
		{
			*p1++ = tmp%10 +'0';
			tmp /= 10;
		}while(tmp);

		//逆置
		char *pend = p1-1;

		for(;pstart<pend;pstart++,pend--)
		{
			char ch = *pstart;
			*pstart = *pend;
			*pend=ch;
		}

		if(length>1)
			*p1++ = '.';
		length--;

		//循环条件转换
		p--;
	}
	*p1 ='\0';
	return 1;

}


下面是我的答案:Ip转换到整数

int Ip_to_Int(char *Ipstr)
{
	if(NULL == Ipstr || '\0' == *Ipstr)
		return 0;

	char *pEntry = 0;
	char *pEnd = 0;
	int temp = 0;//用于记录转换后数字
	int Resule = 0;
	int count = 0;//用于记录.的个数 根据这个来移位
	int len = 0;//用于记录两个指针间的差

	pEntry = pEnd = Ipstr;

	if(*pEntry >'9' || *pEntry < '0')//如果第一个字符不是数字就返回了
		return 0;

	for (int i = 0; *pEnd != '\0'; i++)
	{
		if(*pEntry >'9' || *pEntry <'0')//不是这个范围就说明不是数字
			return 0;

		if(*pEnd == '.')
		{
			
			len = pEnd - pEntry;

			for (int k = 0; k <len; k++)
			{
				temp = temp * 10 + (*pEntry  - '0');
				pEntry ++;
			}

			if(temp >255)//大于255说明不是IP
				return 0;

			Resule |= temp<<(count*8);
			count ++;
			//printf("Resule :0x%p\n",Resule);
			temp = 0;
			pEnd ++;//pEnd指向. 应该指向下一个有效数字
			pEntry = pEnd;
		}

		pEnd ++;
	}

	//最后一个不能用.为标志了
	temp = 0;
	len = pEnd - pEntry;
	for (int j = 0; j < len; j++)
	{
		temp = temp * 10 + (*pEntry  - '0');
		pEntry ++;
	}
	Resule |= temp<<24;

	return Resule;
	//192.168.1.1 0x0101a8c0
}

至于整数到IP 我直接使用了sprintf 作弊了 哈哈

char* Int_to_IP(unsigned int Ip,char* buff)
{
	sprintf(buff,"%u.%u.%u.%u",
		(unsigned char)(*(char*)&Ip),
		(unsigned char)(*(char*)((char*)&Ip + 1)),
		(unsigned char)(*(char*)((char*)&Ip + 2)),
		(unsigned char)(*(char*)((char*)&Ip + 3))
		);

	return buff;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值