How to write a complete C code that uses stack to realize binary conversion to hexadecimal
This article shows you how to write a complete C code that uses the stack to convert hexadecimal to hexadecimal. The content is concise and easy to understand, which will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.
/ * convert binary to decimal * / # include#include#define INCREMENT 8typedef char Elemtype;typedef struct Stack {Elemtype * top; Elemtype * base; int stackSize;} Stack;Stack * initStack (int n) / / stack initialization function {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) / / stack function {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) / / unstack function {if (s-> top = = s-> base) exit (0); return (*-- (s-> top)) } int StackLen (Stack * s) / / find the number of elements in the stack {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 ("Please enter binary numbers:\ n") Scanf ("% c", & element); while (element! ='\ n') {/ / Stack the binary number in character type, enter Push (s, element) at the end of the carriage return number; scanf ("% c", & element);} length = StackLen (s) While (StackLen (s)) {for (I ='0' & & temp)