编程将二进制IP地址转换成十进制
[cpp]
/******************************************************************
* Name: IP Address
* Funcion: To convert binary numbers to decimal numbers
* Input: 0000 0011 1000 0000 1111 1111 1111 1111
* Output: 3.128.255.255
**********************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#include<assert.h>
using namespace std;
void convert(char input[],unsigned char output[])//这里的output必须为无符号型,否则必然出错
{
int count = -1,i;
for( i = 0; i < 32; i++ )
{
if( i % 8 == 0 )
count++;
if( input[i] == '1' )
{
switch( i % 8 )
{
case 0:
output[count] += 128;
break;
case 1:
output[count] += 64;
break;
case 2:
output[count] += 32;
break;
case 3:
output[count] += 16;
break;
case 4:
output[count] += 8;
break;
case 5:
output[count] += 4;
break;
case 6:
output[count] += 2;
break;
case 7:
output[count] += 1;
break;
default:
break;
}
}
}
}
/************************************
增加难度 输入和输出都有句点分割 输入输出均表示为点分形式
************************************/
void binaryStringToInt(char binary[],int *data)
{
int n=strlen(binary);
for(int i=0;i<n;i++)
{
*data+=(binary[i]-'0')<<n-i-1; //记得要 -'0' 谨记
}
}
void test1()
{
char i[]="11011";
int d=0;
binaryStringToInt(i,&d);
cout<<"d= "<<d<<endl;
}
int IP_convert(char input[],char output[])
{
assert(NULL!=input);
assert(NULL!=output);
int count=0;
char temp[50]={0};
//char *s=strtok(input, '.'); 谨记:strtok second parameter is "" instead of ''
char *s=strtok(input, ".");
if(s==NULL)
{
cout<<"input error"<<endl;
return -1;
}
while(s != NULL)
{
//cout<<s<<endl;
binaryStringToInt(s,&count); //求二进制字符串对应的整数值
//cout<<"count= "<<count<<endl;
itoa(count,temp,10); //将得到的数字转化为字符串
count=0; //一定要记得count 清零
strcat(output,temp); //连接到目的字符串
strcat(output,"."); // 每一段添加一个点,但是最后会多一个点
s = strtok(NULL, "."); //继续分割元字符串
}
int i=0;
while(output[i]!='\0')i++;
output[--i]='\0'; //消除最后多余的句点
return 0;
}
void test()
{
char input[32];
unsigned char output[4]={0};
gets(input);
convert(input,output);
printf( "%d.%d.%d.%d\n", output[0], output[1], output[2], output[3] );
cout<<"---------------------------------"<<en
补充:软件开发 , C++ ,