整数ip地址转化为01二进制表示...

本文提供了一个简化CCNA中子网划分和IP地址转换过程的小应用,通过自动处理IP地址,避免手动计算的繁琐,实现IP到二进制的快速转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <algorithm>
#include <memory.h>
using namespace std;
int indexof(string ipaddress, char spliter)
{
    for(int i = 0 ; i< ipaddress.length() ;i ++)
        if(ipaddress[i] == spliter)
        return i;
    return -1;
}

string *  split(string ipaddress, char spliter,int &count)
{
  
   string *b = new string[4];
  
      while(ipaddress.length() >= 0 )
      {
      
        //cout<<indexof(ipaddress,spliter)<<endl;
        int indexofspliter = indexof(ipaddress,spliter);
        if(indexofspliter != -1)
        {
         b[count++]= ipaddress.substr(0,indexofspliter);
         ipaddress = ipaddress.substr(indexofspliter+1,ipaddress.length());
        // cout<<ipaddress<<" is ip"<<endl;
        }
        else 
        {
            b[count++]= ipaddress;
            break;
        }
      }
    return b;
}
int  stringtochararray(string temp)
{
  int size = temp.length();
  int time = 0;
  int result = 0;
  while(time < size )
  {
  	result *= 10;
  	result += temp[time++] - '0';
  } 
  return result;
}
int main()
{
      int splitercount = 0 ;
      string ip;
      cout<<"输入你要转换的Ip"<<endl;
      string * ipstring  = NULL;
      int currentipaddress = 0;
      char ipbinary[32];
      while(1)
      {
	        cin>>ip;
	        splitercount = 0 ;
	        ipstring = split(ip,'.',splitercount);
	        currentipaddress = 0;
	      
	        for(int i= 0 ; i< 32;i ++)
	            ipbinary[i] = '0';
	        int count = 31;
	        while(currentipaddress < splitercount)
	        {	    	           
		        int intipaddress = stringtochararray(ipstring[currentipaddress]);
		        int tempcount = count - 7;
		        count -= 8;
		      	while(intipaddress > 0)
		        {
		            ipbinary[tempcount++] = intipaddress%2 + '0';   
		         	intipaddress/=2;	
		        }
		        currentipaddress++;
		        }
		 
		       for(int i = 31; i >= 0 ; i --)
		       {
		           if(i != 31 &&(i+9)%8 == 0 )
		           cout<<".";
		        cout<<ipbinary[i];
		       }
		        cout<<endl;
           }
}
打算写一个小的应用,主要是针对CCNA中的一些繁琐的问题,如子网划分等,不想手算啊
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值