二进制----->十进制
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXSIZE 1024 //初始化栈有1024个空间
#define ADD_MAXSIZE 100 //栈内存不够时增加100个空间
typedef char ElemType;
typedef struct
{
ElemType *top; //指向栈顶的指针变量
ElemType *base; //指向栈底 的指针变量
int stackSize; //栈可使用的最大容量
}SeqStack;
//初始化
void InitStack(SeqStack *s)
{
s->base=(ElemType*)malloc(MAXSIZE*sizeof(ElemType));
if(s->base==NULL)
exit(0);
s->top=s->base;
s->stackSize=MAXSIZE;
}
//入栈
void Push(SeqStack *s,ElemType e)
{
if(s->top-s->base>=s->stackSize)
{
s->base=(ElemType*)realloc(s->base,(ADD_MAXSIZE+s->stackSize)*sizeof(ElemType));
if(s->base==NULL)
exit(0);
}
*(s->top)=e;
s->top++;
}
//出栈
ElemType Pop(SeqStack *s)
{
if(s->top==s->base)
{
printf("占空了");
}
return *--(s->top);
}
//计算栈当前的容量
int StackLen(SeqStack s)
{
return (s.top-s.base);
}
int main()
{
ElemType c;
SeqStack s;
int len,i,sum=0;
InitStack(&s);
printf("请输入二进制数,输入#停止\n");
scanf("%c",&c);
while(c!='#')
{
Push(&s,c);
scanf("%c",&c);
}
getchar();
len=StackLen(s);
printf("栈的容量为:%d\n",len);
for(i=0;i<len;i++)
{
c=Pop(&s);
sum+=(c-48)*pow(2,i);
}
printf("十进制数为:%d",sum);
return 0;
}
二进制------>八进制
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAXSIZE 1024 //初始化栈有1024个空间
typedef char ElemType;
typedef struct
{
ElemType *top; //指向栈顶的指针变量
ElemType *base; //指向栈底 的指针变量
int stackSize; //栈可使用的最大容量
}SeqStack;
//创建栈
void InitStack(SeqStack *s)
{
s->base=(ElemType*)malloc(MAXSIZE*sizeof(ElemType));
if(!s->base)
exit(0);
s->top=s->base;
s->stackSize=MAXSIZE;
}
//判断栈是否为空
int Isempty(SeqStack *s)
{
if(s->base==s->top)
return 0;
return 1;
}
//出栈
int SeqStack_Pop(SeqStack *s)
{
if(Isempty(s))
{
return *--(s->top);
}
printf("栈为空返回失败\n");
return -1;
}
//入栈
void Stack_Push(SeqStack *s,ElemType vue)
{
if(s->top-s->base>=MAXSIZE)
{
s->base=(ElemType*)realloc(s->base,2*MAXSIZE*sizeof(ElemType));
s->top=s->base+s->stackSize;
s->stackSize=MAXSIZE*2;
}
*(s->top)=vue;
s->top++;
}
int main()
{
SeqStack s1,s2;
InitStack(&s1);
InitStack(&s2);
ElemType e;
int num=0;
printf("请输入一个二进制数:输入#截止");
scanf("%c",&e);
while(e!='#')
{
Stack_Push(&s1,e);
scanf("%c",&e);
}
getchar();
while(s1.base!=s1.top)
{
for(int i=0;i<3;i++)
{
e=SeqStack_Pop(&s1);
num+=(e-48)*pow(2,i);
}
Stack_Push(&s2,num);
}
while(s2.base!=s2.top)
{
e=SeqStack_Pop(&s2);
printf("%d ",e);
}
return 0;
}