#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#include<math.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
struct SqStack{
int *base;
int *top;
int stacksize;
};
int InitStack ( struct SqStack *s){
int *newbase;
newbase= (int *)malloc(STACK_INIT_SIZE*sizeof(int));
if(!newbase)
return 0;
s->base=newbase;
s->top = s->base ;
s->stacksize = STACK_INIT_SIZE ;
return 1;
}//构建一个栈
int GetTop(SqStack *s,int e){
if(s->top==s->base)
return 0;
e=*(s->top-1);
return 1;
}//若栈不空,则用e返回当前的栈顶元素
int push(SqStack *s,int e){
if(s->top-s->base>=s->stacksize){
s->base = (int *)realloc(s->base,(STACK_INIT_SIZE+STACKINCREMENT)*sizeof(int));
if(!s->base)
return 0;
s->top=s->base+s->stacksize;
s->stacksize = s->stacksize +STACKINCREMENT;
}
*s->top++=e;
return 1;
} //插入元素e为新的栈顶元素
int pop(SqStack *s,int &e){
if(s->top==s->base)
return 0;
e=*--s->top;
return 1;
}//删除S的栈顶元素
int StackEmpty(SqStack s){
if(s.base==s.top)
return 1;
else
return 0;
}//判断该栈是否为空
void ClearStack(struct SqStack &s){
if(!StackEmpty(s))
s.top=s.base;
}
//清空一个栈
int changeNumber(struct SqStack &s,int n,int prem,int nowm){
int i=0,sum=0,pop=0;
switch(prem)
{
case 2:{
switch(nowm)
{
case 2:return n;break;
case 8:
{ n=changeNumber(s,n,prem,10);
printf("the stack is null\n%d",prem);
changeNumber(s,n,10,nowm);
}break;
case 10:
while(n!=0)
{
pop=(int)((n%10)*pow(2,i));
push(&s,pop);
n=n/10;
i++;
if(!StackEmpty(s))
GetTop(&s,pop);
sum+=pop;
}break;
return sum;
case 16:break;
}
}break;
case 8:{
switch(nowm)
{
case 2:push(&s,n);break;
case 8:push(&s,n);break;
case 10:
while(n!=0)
{
push(&s,int(n*pow(2,i)));
n=n%10;
i++;
}break;
case 16:
while(n!=0)
{
n=n%10;
push(&s,int(n*pow(8,i)));
i++;
}break;
}
}break;
case 10:{
switch(nowm)
{
case 2:
while(n!=0)
{
push(&s,n%2);
n=n/2;
}break;
case 8:
{
while(n!=0)
{
push(&s,n%8);
n=n/8;
}
sum=changeNumber(s,n,prem,nowm);
printf("%d",sum);
}break;
case 10:push(&s,n);break;
case 16:
while(n!=0)
{
push(&s,n%16);
n=n/16;
}break;
}
}break;
case 16:;break;
}
return 0;
}
void main(){
struct SqStack s ;
int e,n,prem,nowm,sum;
InitStack(&s);
printf("请输入任意一进制的一个数:");
scanf("%d",&n);
printf("请输入该数的进制数:");
scanf("%d",&prem);
printf("请输入要转换成的进制:");
scanf("%d",&nowm);
if(prem!=10){
sum=changeNumber(s,n,prem,nowm);
printf("%d",sum);
}
else
{
changeNumber(s,n,prem,nowm);
while(!StackEmpty(s))
{
pop(&s,e);
switch(e)
{
case 10:printf("%c",'A');break;
case 11:printf("%c",'B');break;
case 12:printf("%c",'C');break;
case 13:printf("%c",'D');break;
case 14:printf("%c",'E');break;
case 15:printf("%c",'F');break;
default :printf("%d\n",e);
}
}
}
}