IP地址转换

 1 /*
 2 点分十进制转32位IP
 3 */
 4 #include<iostream>
 5 #include<vector>
 6 #include<string>
 7 using namespace std;
 8 bool change2Binary(const string& str)
 9 {
10     int arrInt[4] = {0};//存放4个IP地址整数 192.168.1.1
11     unsigned k = 0;
12     for (int i = 0; i < 4; i++)
13     {
14         while (k < str.size() && str[k] != '.')
15         {
16             arrInt[i] = arrInt[i] * 10 + str[k] - '0';
17             k++;
18         }
19         k++;
20     }
21     //判断IP地址合法性
22     for (auto c : arrInt)
23         if (c < 0 || c>255) return false;
24     //十进制转换成二进制
25     for (int i = 0; i < 4; i++)
26     {
27         int temp = arrInt[i];
28         vector<int> Bin(8,0);
29         for (int j = 7; temp != 0; j--)
30         {
31             Bin[j] = temp % 2;
32             temp /= 2;
33         }
34         for (auto t : Bin)
35             cout << t;
36         cout << " " <<endl;
37     }
38     return true;
39 }
40 int main(void) {
41     string str;
42     cin >> str;
43     if (!change2Binary(str))
44         cout << "data error" << endl;
45 
46     return 0;
47 }

 

 

/*
二进制转点分十进制
*/
#include<iostream>  
#include<cstring>  
using namespace std;  
bool check(char *str);  //检查串中是否有0/1之外的字符  
int trans(char *str);  //将0/1字符串转换成十进制  
bool check(char *str)  
{  
    int i;  
    for(i=0;i<32;i++)  
        if(str[i]!='1' && str[i]!='0')  
        return false;  
    return true;  
}  
int trans(char *str)  
{  
    int n=0,i;  
    for(i=0;i<8;i++)  
    {  
        if(str[i]=='1')  
            n=n*2+1;  
        else  
            n=n*2;  
    }  
    return n;  
}  
int main()  
{  
    char IP[33];  
    cout<<"32位二进制IP地址:"<<endl;  
    cin>>IP;  
    if(strlen(IP)!=32)  
        cout<<"IP地址长度应为32位"<<endl;  
    else  
    {  
        if(!check(IP))  
            cout<<"IP串中有0/1外字符"<<endl;  
        else  
        {  
            //四次调用trans()分别转换四组二进制数  
            cout<<"IP地址对应的点分十进制:"<<endl;  
            cout<<trans(IP)<<"."<<trans(IP+8)<<"."<<trans(IP+16)<<"."<<trans(IP+24)<<endl;  
        }  
    }  
    return 0;  
}  

 

posted on 2018-01-18 16:18  wsw_seu  阅读(365)  评论(0编辑  收藏  举报

导航