IP网络(IP Networks)

本文介绍了一种通过逻辑运算处理IP地址的方法,包括IP地址的或、与、异或操作,以及如何通过这些运算确定子网段和掩码。通过对输入的IP地址进行位运算,文章详细解释了如何找出共同的网络部分,并计算出子网掩码。

在这里插入图片描述

在这里插入图片描述

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cmath>
typedef long long ll;
using namespace std;
int main()
{
 ll ip_or;
 ll ip_and;
 ll ip_xor;
 ll mask;
 ll segment;
 int n;
 ll temp;
 ll num1,num2,num3,num4;
 char ch;
 while(cin>>n)
 {
  cin>>num1>>ch>>num2>>ch>>num3>>ch>>num4;
  temp=0;
  temp+=(num1<<24)+(num2<<16)+(num3<<8)+num4;
  ip_or=ip_and=temp;
  while(--n)
  {
   cin>>num1>>ch>>num2>>ch>>num3>>ch>>num4;
   temp=0;
   temp+=(num1<<24)+(num2<<16)+(num3<<8)+num4;
   ip_or=ip_or|temp;
   ip_and=ip_and&temp;
  }
  ip_xor=ip_or^ip_and;
  int bit=log2(ip_xor*2+1);
  mask=0xFFFFFFFF;
  mask=(mask>>bit)<<bit;
  segment=ip_or&mask;
  cout << ((segment >> 24) & 0x0FF) << "." << ((segment >> 16) & 0x0FF) << "." << ((segment >> 8) & 0x0FF) << "." << (segment & 0x0FF) << endl;
  cout << ((mask >> 24) & 0x0FF) << "." << ((mask >> 16) & 0x0FF) << "." << ((mask >> 8) & 0x0FF) << "." << (mask & 0x0FF) << endl;
 }
 return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

【执珪】瑕瑜·夕环玦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值