本篇文章为大家展示了怎么编写利用栈实现二进制转换十六进制的完整C代码,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
/* 二进制转换为十进制 */ #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; }
上述内容就是怎么编写利用栈实现二进制转换十六进制的完整C代码,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。