您的位置:首页 > 编程语言

利用栈实现二进制转换十六进制的完整C代码

2014-11-19 12:48 363 查看
/* 二进制转换为十进制 */

#include<stdio.h>
#include<stdlib.h>

#define INCREMENT 8

typedef char Elemtype;
typedef struct Stack {
	Elemtype *top;
	Elemtype *base;
	int stackSize;
}Stack;

Stack *initStack( int n )					//栈初始化函数
{
	Stack *s = (Stack *)malloc(sizeof(Stack));
	s -> base = ( Elemtype * )malloc( sizeof(Elemtype) * n );
	if ( s -> base == NULL )
		exit(0);
    s -> top = s -> base;
	s -> stackSize = n;
	return s;
}

void Push( Stack *s, Elemtype e )  //入栈函数
{
	if( s->top - s->base >= s->stackSize ) {
		s -> base = (Elemtype *)realloc( s->base, s->stackSize + INCREMENT * sizeof(Elemtype) );
		if( !s->base )
			exit(0);
		s->top = s->base + s->stackSize;
		s->stackSize = s->stackSize + INCREMENT;
		}
		*(s->top) = e;
		s->top++;
}

Elemtype Pop( Stack *s ) //出栈函数
{
	if( s->top == s->base ) 
		exit(0);
	return ( *--(s->top) );
}

int StackLen( Stack *s)  //求栈内元素数量
{
	return ( s->top - s->base );
}

int main()
{
	int length;
	int i;
	short int  sum = 0;
	int index;
	int temp;

	Elemtype element;
	Stack *s = initStack( 16 );
	Stack *p = initStack( 8 );

	printf("请输入二进制数:\n");	
	scanf("%c", &element);
	while( element != '\n' ) {   //将二进制数以字符型入栈,回车号结束输入
			Push( s, element );	
			scanf("%c", &element);
	}	

	length = StackLen( s );

	while( StackLen( s ) ) {
		for( i=0,sum=0,index=1; (i<4)&&(StackLen(s)); i++ ) {  //进制转换  '1' ----- ASC码为49	
			sum = sum + (Pop(s)-48) * index;
			index *= 2;	}
		Push( p, sum );
	}

	printf("转换十六进制数为:\n");
	while( StackLen(p) ) {
		temp = Pop(p);
		if( temp >= '0' && temp <= '9' )
			printf("%d", temp);
		else
			printf("%c", temp+'A'-10);
	}

	printf("\n");
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: