算法:整数与ip地址转换

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

  1.  
    #include <string>
  2.  
    #include <iostream>
  3.  
    using namespace std;
  4.  
    int shu[4]={0};
  5.  
    int IPtoINT(string s){
  6.  
    int i,a=0,c=0,p=0;
  7.  
    for(i=0;i<s.length();i++)
  8.  
    {
  9.  
    if(s[i]!='.')
  10.  
    {
  11.  
    a=a*10+(s[i]-'0');
  12.  
    }else{
  13.  
    if(a>=0&&a<=255)
  14.  
    {
  15.  
    shu[p++]=a;
  16.  
    c++;
  17.  
    }else
  18.  
    {//cout<<"NO"<<endl;
  19.  
    return 0;}
  20.  
     
  21.  
    }
  22.  
    }
  23.  
    if(c!=3)
  24.  
    {//cout<<"NO"<<endl;
  25.  
    return 0;}
  26.  
    else
  27.  
    {if(a>=0&&a<=255)
  28.  
    {
  29.  
    shu[p++]=a;
  30.  
    }else
  31.  
    {//cout<<"NO"<<endl;
  32.  
    return 0;}
  33.  
     
  34.  
    }
  35.  
    //cout<<"YES"<<endl;
  36.  
    return 1;
  37.  
    }
  38.  
    void INTtoIP(long s)
  39.  
    {
  40.  
    shu[0]=s&255;
  41.  
    shu[1]=(s&(255*256))/256;
  42.  
    shu[2]=(s&(255*256*256))/(256*256);
  43.  
    shu[3]=(s&(255*256*256*256))/(256*256*256);
  44.  
    }
  45.  
    void main(){
  46.  
    string ips;
  47.  
    long ipint,stoint=0;
  48.  
    int i;
  49.  
    cin>>ips;
  50.  
    cin>>ipint;
  51.  
    if(IPtoINT(ips))
  52.  
    {
  53.  
    for(i=0;i<4;i++)
  54.  
    stoint=stoint*256+shu[i];
  55.  
    cout<<stoint<<endl;
  56.  
    }
  57.  
    INTtoIP(ipint);
  58.  
    if(shu[0]<256&&shu[1]<256&&shu[2]<256&&shu[3]<256)
  59.  
    {
  60.  
    cout<<shu[3]<<'.'<<shu[2]<<'.'<<shu[1]<<'.'<<shu[0]<<endl;
  61.  
    }
  62.  
    }
原文地址:https://www.cnblogs.com/lidabo/p/9650147.html