算法:整数与ip地址转换

rt


直接上代码(不要直接拷贝,中间少了一行啊):



#include <string>
#include <iostream>
using namespace std;
int shu[4]={0};
int IPtoINT(string s){
	int i,a=0,c=0,p=0;
	for(i=0;i<s.length();i++)
	{
		if(s[i]!='.')
		{
			a=a*10+(s[i]-'0');
		}else{
			if(a>=0&&a<=255)
			{
				shu[p++]=a;
				c++;
			}else
			{//cout<<"NO"<<endl;
				return 0;}
			
		}
	}
	if(c!=3)
	{//cout<<"NO"<<endl;
		return 0;}
	else
		{if(a>=0&&a<=255)
		{
			shu[p++]=a;
		}else
		{//cout<<"NO"<<endl;
			return 0;}
		
		}
		//cout<<"YES"<<endl;
		return 1;
}
void INTtoIP(long s)
{
   shu[0]=s&255;
   shu[1]=(s&(255*256))/256;
   shu[2]=(s&(255*256*256))/(256*256);
   shu[3]=(s&(255*256*256*256))/(256*256*256);
}
void main(){
string ips;
long ipint,stoint=0;
int i;
cin>>ips;
cin>>ipint;
if(IPtoINT(ips))
{
  for(i=0;i<4;i++)
  stoint=stoint*256+shu[i];
  cout<<stoint<<endl;
}
INTtoIP(ipint);
if(shu[0]<256&&shu[1]<256&&shu[2]<256&&shu[3]<256)
{
    cout<<shu[3]<<'.'<<shu[2]<<'.'<<shu[1]<<'.'<<shu[0]<<endl;
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值