编程将二进制IP地址转换成十进制
2013-04-19 11:32
363 查看
/****************************************************************** * 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<<"---------------------------------"<<endl; } int main() { //test1(); char i[]="00001101.00001111.00000001.00001010"; char o[10]={0}; IP_convert(i,o); puts(o); return 0; }
相关文章推荐
- 二进制转换成十进制、及约瑟夫问题
- 简单的利用栈 将二进制转换成十进制
- 二进制转换成十进制显示输出
- ip地址转换成十进制整数
- 二进制转换成十进制
- SQL 二进制转换成十进制方法
- 8、编写一个程序,它先将键盘上输入的一个字符串转换成十进制整数, 然后打印出这个十进制整数对应的二进制形式。
- 将任意二进制转换成十进制
- 十进制转换成二进制,十进制小数转换成二进制小数,二进制转换成十进制
- 将二进制转换为其它进制(这里转化为16进制,其它自己尝试)
- java中各进制之间的转换(十进制转十六进制、十进制转二进制、二进制转十进制、二进制转十六进制)
- pta中 字符串转换成十进制整数
- PowerShell把IP地址转换成二进制的方法
- GNU Linux shell中如何进行各进制编码间(二进制、8进制、16进制、base64)的转换
- 将二进制转换为其它进制(这里转化为16进制,其它自己尝试)
- Python中不同进制互相转换(二进制、八进制、十进制和十六进制)
- 数组-08. 字符串转换成十进制整数
- 数组-08. 字符串转换成十进制整数(15)
- 字符串中16进制数字转换成十进制输出
- 将二进制转换为其它进制(这里转化为16进制,其它自己尝试)