在 C 中使用堆栈将二进制转换为十进制

Binary to Decimal using Stack in C

C中使用栈将二进制转十进制的代码。 我在转换后使用堆栈存储总和,并仅从包含总和的堆栈中弹出顶部元素。 请提出任何优化建议。

#include<stdio.h>
#include<conio.h>
#define MAX 100
int stack[MAX];
int top=-1;
int num;
void push();
void pop();
main()
{
    printf("Enter the binary number: ");
    scanf("%d",&num);
    push();
    pop();
}
void push()
{
    int rem;
    
        int dec_value = 0;
        int base = 1;
        int temp = num;
        while(temp)
        {
            int last_digit = temp % 10;
            temp = temp / 10;
            dec_value += last_digit * base;
            base = base * 2;
                
        if(top>=MAX)
        {
            printf("\nSTACK OVERFLOW!");
        }
        else
        {
            top++;
            stack[top]=dec_value;
        }
    }
}
void pop()
{
    int i;
    printf("Its decimal form: ");
    printf("%d",stack[top]);
    if(top<0)
    {
        printf("\nStack is empty!");
    }
}

建议:

  • 读取一串二进制数字:这在转换为 32 位无符号整数时最多允许 32 位二进制数字,而不是如果您读取 int 时仅允许 10 位二进制数字。
  • 无需堆栈即可进行转换:您只需要在循环遍历字符串时进行移位。

这是一种可能性。请注意,输入未彻底检查。

#include <stdio.h>
#include <inttypes.h>

#define N 33

int main(void) {
    char bits[N];
    char *c;
    uint32_t n = 0;
    
    fgets(bits, N, stdin);
    for (c = &bits[0]; *c != '\n' && *c != 0; c++) {
        n = (n << 1) | (*c == '1');
    }
    printf("%u\n", n);
    return 0;
}