7-7 IP地址转换(20 分)

一个IP地址是用四个字节(每个字节8个位)的二进制码组成。
请将32位二进制码表示的IP地址转换为十进制格式表示的IP地址输出。

输入格式:
输入在一行中给出32位二进制字符串。

输出格式:
在一行中输出十进制格式的IP地址,其由4个十进制数组成(分别对应4个8位的二进制数),中间用“.”分隔开。

输入样例:
11001100100101000001010101110010
输出样例:
204.148.21.114
 

#include<iostream>
using namespace std;
int main()
{
    int a[4]={0},b[4][8];
	int arr[8]={128,64,32,16,8,4,2,1};
    string str;
    cin>>str;
    int x=0;
    for(int i = 0; i<4;i++)
    {
        for(int j = 0+x; j<8+x; j++)
        {
            if(str[j]-'0'==1)
            {
                a[i]=a[i]+ arr[j-x];
            }
        }
        if(x<24)
        {
           x=x+8;
        }
    }
    int first=1;
    for(int j=0;j<4;j++)
    {
        if(first==0)
            cout<<".";
        else
            first=0;
        cout<<a[j];
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40099908/article/details/81610650
今日推荐