二进制转十进制--(栈)

/*****************
*每个二进制数转换成相应的十进制数方法如下:
*(XnXn-1……X3X2X1)2 = X1*2^0+X2*2^1+…+Xn*2^(n-1)
*一个二进制数要转换为相应的十进制数,就是从最低位起用每一位去乘以对应位的积,也就是说用第n位去乘以2^(n-1),然后全部加起来。
***************/
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define OK 1
#define ERROR 0
#define STACK_INIT_SIZE 10
#define STACKINCREMENT 5
typedef int ElemType;
typedef int STATUS;
typedef struct Stack {
	ElemType * top;
	ElemType *base;
	int stackSize;
}stack;
STATUS initStack(stack * s)
{
	s->base = (ElemType*)malloc(STACK_INIT_SIZE * sizeof(ElemType));
	s->top = s->base;
	s->stackSize = STACK_INIT_SIZE;
	return OK;
}
STATUS Push(stack *s, ElemType e)
{
	if (s->top - s->base >= s->stackSize)
	{
		s->base = (ElemType*)realloc(s->base, (s->stackSize + STACKINCREMENT) * sizeof(ElemType));
		if (!s->base)return ERROR;
		s->top = s->base + s->stackSize;
		s->stackSize = s->stackSize + STACKINCREMENT;
	}
	*(s->top) = e;
	s->top++;
	return OK;
}
STATUS Pop(stack *s, ElemType * e)
{
	if (s->base == s->top)return ERROR;
	--s->top;
	*e = *(s->top);
	return OK;
}
STATUS clearStack(stack *s)
{
	s->top = s->base;
	return OK;
}
STATUS destoryStack(stack *s)
{

	//for (int i = 0; i < s->stackSize; i++)
	//	{
	free(s->base);
	//	s->base++;
	//	}
	//	printf("%d", *(s->base));
	s->base = 0;
	s->top = 0;
	s->stackSize = 0;
	return OK;
}
int main(int argc, char * argv[])
{
	stack s;
	int data,sum=0,j=0;
	ElemType e = 555, q;
	initStack(&s);
	printf("请输入二进制数每输入一位回车。(-1结束):\n");
	scanf("%d", &data);
	Push(&s, data);
	while (1)
	{
		scanf("%d", &data);
		if (data == -1)break;
		Push(&s, data);
	};
	//开始计算
	while (Pop(&s, &data) == OK)
	{
		sum += data*pow(2, j);
		++j;
	}
	printf("\n十进制数为:%d\n", sum);
	//清理
	clearStack(&s);
	destoryStack(&s);
	system("pause");
	return 0;
}

    原文作者:进制转换
    原文地址: https://blog.csdn.net/u012997311/article/details/79154585
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞