计算IP地址所在网段

给定一个IP地址和一个子网掩码, IP地址跟子网掩码二进制按位与计算之后的结果代表网段地址。
例如192.168.1.1(11000000 10101000 00000001 00000001)与子网掩码255.255.255.240(11111111 11111111 11111111 11110000)二进制按位与之后为192.168.1.0(11000000 10101000 00000001 00000000),子网掩码的前28位为1即掩码长度为28位,故该IP地址和子网掩码组合下的网段为192.168.1.0/28
给出一个IP地址和一个子网掩码,计算他们的网段并按照格式输出。
输入描述:
IP地址 子网掩码,两个字段之间用空格分隔。给出的IP地址和子网掩码均合法。
输出描述:
网段地址/掩码长度 其中网段地址为IP地址跟子网掩码二进制按位与的结果,掩码长度为子网掩码转换为二进制后“1”的个数,中间使用“/”隔开
示例1:
输入:
192.168.1.1 255.255.255.0
输出:
192.168.1.0/24
示例2:
输入:
192.168.0.1 0.0.0.0
输出:
0.0.0.0/0

#include<iostream>
#define Length 4
using namespace std;

void printIntArray(int* array) {
	for (int i = 0; i < Length; i++)
		cout << array[i] << "  ";
	cout << endl;
}

int charToInt(char ch, int sum) {
	int result = sum * 10 + (ch - '0');
	return result;
}

void getIntOfIp(char* ip, int* intArray) {
	int count = 0;
	int temp = 0;
	while (*ip != '\0') {

		if (*ip == '.') {
			intArray[count] = temp;
			count++;
			temp = 0;
		}
		else if (count == 0) {
			temp = charToInt(*ip, temp);
		}
		else if (count == 1) {
			temp = charToInt(*ip, temp);
		}
		else if (count == 2) {
			temp = charToInt(*ip, temp);
		}
		else if (count == 3) {
			temp = charToInt(*ip, temp);
		}
		ip++;
	}
	intArray[count] = temp;
}

void ipAndSubIP(int* nums1, int* nums2, int* nums3) {
	for (int i = 0; i < Length; i++) {
		nums3[i] = nums1[i] & nums2[i];
	}
}

void getFlagToString(int* nums, char* ch) {
	int count = 0;
	for (int i = 0; i < Length; i++) {
		int num = nums[i];
		int getH = num / 100;
		int getM = num / 10 % 10;
		int getL = num % 10;
		if (getH) {
			ch[count++] = getH + '0';
			ch[count++] = getM + '0';
		}
		else if (getM) {
			ch[count++] = getM + '0';
		}
		ch[count++] = getL + '0';
		ch[count++] = '.';
	}
	ch[count - 1] = '\0';
}

int getResult(char* ip, char* subNet, char* ch) {
	// 取出ip的整数值
	int count = 0;
	int ip1Array[Length], ip2Array[Length], ip3Array[Length],flag1Array[Length];
	getIntOfIp(ip, ip1Array);
	getIntOfIp(subNet, ip2Array);
	getIntOfIp(subNet, ip3Array);
	for (int i = 0; i < Length; i++){
		while (ip3Array[i]) {
			if (ip3Array[i] & 1) {
				++count;
			}
			ip3Array[i] = ip3Array[i] >> 1;
		}
	}

	ipAndSubIP(ip1Array, ip2Array, flag1Array);

	getFlagToString(flag1Array, ch);
	return count;
}

int main(void) {

	// 输入一个ip, 一个子网掩码
	char ip[18], subNet[18];
	cin >> ip >> subNet;
	char ch[18];
	int result = getResult(ip, subNet, ch);

	cout << ch << "/" << result << endl;
	return 0;
}
  • 4
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值