怎么编写利用栈实现二进制转换十六进制的完整C代码
栈是一个非常有用的数据结构,可以用于实现许多算法和操作。在本篇文章中,我们将介绍如何使用栈来实现二进制转换为十六进制。
二进制和十六进制是计算机科学中最常用的数字系统。二进制只有两个数字,0和1,十六进制有16个数,分别是0到9,以及A到F。
在这个过程中,我们需要把一个二进制数字转换为十六进制。这个过程包括以下步骤:
1. 从右到左,每4个二进制数字组成一组。
2. 将这组数字转换为十六进制。
3. 将所有的十六进制组合在一起。
为了实现这个过程,我们可以使用栈来存储和操作每个二进制数字。我们的算法将使用以下步骤:
1. 首先,我们需要把二进制数字从右到左一个个压入栈中,这样我们就可以从左到右处理它们。
2. 然后,我们需要每四个数字一组,把它们弹出栈并转换为对应的十六进制数字,并将它们压回栈中。
3. 最后,我们将栈中所有的十六进制数字按顺序弹出并组合成一个十六进制数字。
下面是用C代码实现这个算法的步骤:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAXSIZE 100
typedef struct{
int top;
char stack[MAXSIZE];
} Stack;
void init(Stack *s){
s->top = -1;
}
bool isEmpty(Stack *s){
if(s->top == -1){
return true;
}else{
return false;
}
}
bool isFull(Stack *s){
if(s->top == MAXSIZE - 1){
return true;
}else{
return false;
}
}
void push(Stack *s, char data){
if(isFull(s)){
printf("Stack is full!
");
exit(1);
}else{
s->top++;
s->stack[s->top] = data;
}
}
char pop(Stack *s){
if(isEmpty(s)){
printf("Stack is empty!
");
exit(1);
}else{
s->top--;
return s->stack[s->top + 1];
}
}
int main(){
Stack binaryStack;
init(&binaryStack);
char binary[MAXSIZE];
printf("Enter a binary number: ");
scanf("%s", binary);
int len = strlen(binary);
for(int i = 0; i < len; i++){
push(&binaryStack, binary[i]);
}
Stack hexStack;
init(&hexStack);
int count = 0;
char temp[5];
temp[4] = '\0';
while(!isEmpty(&binaryStack)){
temp[count] = pop(&binaryStack);
count++;
if(count == 4){
count = 0;
int sum = 0;
int base = 1;
for(int i = 3; i >= 0; i--){
if(temp[i] == '1'){
sum += base;
}
base *= 2;
}
char hex;
if(sum < 10){
hex = sum + '0';
}else{
hex = sum - 10 + 'A';
}
push(&hexStack, hex);
}
}
if(count != 0){
int sum = 0;
int base = 1;
for(int i = count - 1; i >= 0; i--){
if(temp[i] == '1'){
sum += base;
}
base *= 2;
}
char hex;
if(sum < 10){
hex = sum + '0';
}else{
hex = sum - 10 + 'A';
}
push(&hexStack, hex);
}
printf("The hexadecimal conversion is: ");
while(!isEmpty(&hexStack)){
printf("%c", pop(&hexStack));
}
printf("
");
return 0;
}
我们首先定义了一个栈的结构体,其中包含一个整数类型的top,表示栈顶位置,以及一个字符串类型的stack,用于存储数据。
然后我们实现了初始化栈,判断栈是否为空或已满,入栈和出栈操作。
在main函数中,我们首先创建一个空栈binaryStack来存储输入的二进制数字。然后我们从控制台输入二进制字符串,并把每个数字都压入栈中。我们使用strlen函数来获取字符串的长度,并使用循环遍历每个数字,把它们压入栈中。
接着我们创建另一个空栈hexStack来存储转换后的十六进制数字。由于从右到左每四个数字一组进行转换,我们使用一个计数器count来记录当前组有多少个数字,以及一个临时字符串数组temp来存储当前组的数字。当count等于4时,我们把它们弹出栈并转换为对应的十六进制数字,然后把它们压回栈中。
最后,我们把栈中所有的十六进制数字弹出并组合在一起,得到转换后的结果。我们使用一个while循环来遍历栈中的元素,依次打印它们即可。
编译和运行程序后,在控制台输入一个二进制数字,程序将会把它转换为对应的十六进制数字并打印出来。
