# include<stdlib.h>
# include<math.h>
#define STACKINITSIZE 20
# define STACKINCREMENT 10
typedef struct{
char *base;
char *top;
int stackSize;
}sqStack;
void Init(sqStack * s){
s->base = (char *)malloc(STACKINITSIZE * sizeof(char));
if(!s->base) exit(0);
s->top = s->base;
s->stackSize = STACKINITSIZE;
}
void Push(sqStack * s, char e){
//检测是否满
if(s->top - s->base > s->stackSize){
s->base = (char *)realloc(s->base, (s->stackSize+STACKINCREMENT)* sizeof(char));
if(!s->base) exit(0);
s->top = s->base + s->stackSize;
s->stackSize += STACKINCREMENT;
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack * s, char *e){
if(s->top == s->base) exit(0);
*e = *--(s->top);
}
int StackLen(sqStack s){
return (s.top - s.base);
}
int main(){
char c;
sqStack s1, s2;
int len, i,j, sum = 0;
Init(&s1);
printf("请输入二进制数,输入#表示结束");
scanf("%c",&c);
while(c != '#'){
Push(&s1, c);
scanf("%c",&c);
}
getchar();
len = StackLen(s1);
Init(&s2);
//二进制---8进制
for(i=0; i<len; i=i+3){
for(j=0; j<3;j++){
Pop(&s1, &c);
sum+=(c-48) * pow(2, j);//ASCii做0对应48
if(s1.base == s1.top) break;
}
Push(&s2,sum+48);//也要放asc码对应的数字
sum = 0;
}
printf("八进制数是");
while(s2.base != s2.top ){
Pop(&s2,&c);
printf("%c", c);
}
return 0;
}
//二进制--10进制
# include<stdio.h>
# include<stdlib.h>
# include<math.h>
#define STACKINITSIZE 20
# define STACKINCREMENT 10
typedef struct{
char *base;
char *top;
int stackSize;
}sqStack;
void Init(sqStack * s){
s->base = (char *)malloc(STACKINITSIZE * sizeof(char));
if(!s->base) exit(0);
s->top = s->base;
s->stackSize = STACKINITSIZE;
}
void Push(sqStack * s, char e){
//检测是否满
if(s->top - s->base > s->stackSize){
s->base = (char *)realloc(s->base, (s->stackSize+STACKINCREMENT)* sizeof(char));
if(!s->base) exit(0);
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack * s, char *e){
if(s->top == s->base) exit(0);
*e = *--(s->top);
}
int StackLen(sqStack s){
return (s.top - s.base);
}
int main(){
char c;
sqStack s;
int len, i, sum = 0;
Init(&s);
printf("请输入二进制数,输入#表示结束");
scanf("%c",&c);
while(c != '#'){
Push(&s, c);
scanf("%c",&c);
}
getchar();
len = StackLen(s);
for(i=0; i<len; i++){
Pop(&s, &c);
sum+=(c-48) * pow(2, i);//ASCii做0对应48
}
printf("十进制数是:%d",sum);
return 0;
}