通过栈进行进制转换
#include <stdio.h> #include <stdlib.h> #include <math.h> #define OK 1 #define ERROR 0 #define MAXSIZE 10 typedef char ElemType; typedef int Status; typedef struct{ ElemType *top; ElemType *base; int stackSize; }SqStack; //创建一个空栈 Status InitStack(SqStack *S){ S->base=(ElemType*)malloc(MAXSIZE*sizeof(ElemType)); if(!(S->base)) return ERROR; S->top=S->base; S->stackSize=MAXSIZE;//栈的最大容量 } //入栈 Status Push(SqStack *S,ElemType e){ if(S->top-S->base>=S->stackSize){//c和c++中两个地址相减的结果是地址减完的差除以元素所占字节(sizeof(ElemType)) S->base=(ElemType*)realloc(S->base,(MAXSIZE+S->stackSize)*sizeof(ElemType)); if(!(S->base)) return ERROR; S->top=S->base+S->stackSize; S->stackSize=S->stackSize+MAXSIZE; } *(S->top)=e; S->top++; return OK; } void Pop(SqStack *S,ElemType *e){ if(S->top==S->base) return; *e=*--(S->top); } //销毁栈 void DestroyStack(SqStack *S){ int i; int len=S->stackSize; for(i=0;i<len;i++){ free(S->base); S->base++; } S->top=S->base=NULL; S->stackSize=0; } //格式化栈 void ClearStack(SqStack *S){ S->top=S->base; } //计算栈当前容量 int StackLen(SqStack S){ return S.top-S.base; } //二转十 //int main(){ // SqStack S; // int i; // char c; // InitStack(&S); // printf("请输入二进制数,以#结束\n"); // scanf("%c",&c); // while(c!='#'){ // Push(&S,c); // scanf("%c",&c); // } // getchar();//清除键盘缓冲区的回车 // char e; // int sum=0,len=StackLen(S); // for(i=0;i<len;i++){//二进制比较简单,从栈头开始出栈到栈尾,将字符转换成整数的和 // Pop(&S,&e); // sum=sum+(e-'0')*pow(2,i); // } // printf("%d",sum); // DestroyStack(&S); //} //二转八:要构建两个栈,栈一入栈完毕后以3个字符为一组转为数字求和,然后将和转换为字符型后入栈二;最后再将栈二从头开始出栈; //int main(){ // SqStack S,S1; // int i; // char c; // InitStack(&S); // InitStack(&S1); // printf("请输入二进制数,以#结束\n"); // scanf("%c",&c); // while(c!='#'){ // Push(&S,c); // scanf("%c",&c); // } // getchar(); // char e,sum; // int len=StackLen(S); // while(len){ // sum=0; // for(i=0;i<3;i++){ // Pop(&S,&e); // sum=sum+(e-'0')*pow(2,i); // len--; // if(S.top==S.base) break; // }
e=sum+'0'; // Push(&S1,e); // } // len=StackLen(S1); // for(i=0;i<len;i++){ // Pop(&S1,&e); // printf("%c",e); // } //} //二转十六:和转八一样,要考虑一下sum超过9的情况 int main(){ SqStack S,S1; int i; char c; InitStack(&S); InitStack(&S1); printf("请输入二进制数,以#结束\n"); scanf("%c",&c); while(c!='#'){ Push(&S,c); scanf("%c",&c); } getchar(); char e; int sum,len=StackLen(S); while(len){ sum=0; for(i=0;i<4;i++){ Pop(&S,&e); sum=sum+(e-'0')*pow(2,i); len--; if(S.top==S.base) break; } if(sum>=10){ e=(char)(sum-10+'A'); Push(&S1,e); } else{ e=sum+'0'; Push(&S1,e); } } len=StackLen(S1); for(i=0;i<len;i++){ Pop(&S1,&e); printf("%c",e); } }