zoukankan      html  css  js  c++  java
  • 算法:整数与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.  
      }
  • 相关阅读:
    LinQ&EF任我行(一)LinQ to SQL (转)
    WPF数据模板和控件模板
    Sql优化
    SQL锁表语句
    js动态创建dom
    js实现等待n秒后按钮可用
    js关于事件冒泡
    工作流学习(个人总结)
    sql常用函数
    将Datatable序列化为Json对象返回到客户端
  • 原文地址:https://www.cnblogs.com/lidabo/p/9650147.html
Copyright © 2011-2022 走看看