c - C语言中如何将二进制转换为十进制

标签 c

我想将一系列整数转换为十进制。我知道程序,但如何将所有整数作为一个二进制数?

输出必须是这样的:

Enter first binary digit: 0
Enter second binary digit: 0
Enter third binary digit: 0
Enter fourth binary digit: 0
0000 = 0

以下是我编写此任务的方式:

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<conio.h>

int main(void)
    {
        int a[100];
        int n, dec = 0; int power(int, int);

        long int binaryNumber, decimalNumber = 0, j = 1, remainder;  

        printf("Enter first binary number: ");
        scanf("%ld", &a[1]);
        printf("Enter second binary number: ");
        scanf("%ld", &a[2]);
        printf("Enter third binary number: ");
        scanf("%ld", &a[3]);
        printf("Enter fourth binary number: ");
        scanf("%ld", &a[4]);

        for (int i = 0;i<n;i++)
        {
            scanf("%d", &a[i]);
        }

        for (int i = (n - 1);i >= 0;i--)
        {
            dec = (a[i] * power(2, j)) + dec;
            j++;
        }
        printf("binary number of decimal is %d", dec);

        return 0;
    }

最佳答案

嗯,这是简单的数学。第一个二进制数字是 2^0,第二个是 2^1,第三个是 2^2,...

number = first * 1 + second * 2 + third * 4 + forth * 8;

关于c - C语言中如何将二进制转换为十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32560244/

相关文章:

用C语言创建多分支树

c - 从文件中读取并在 c 中使用 strtok()

c - 错误: called object '0' is not a function

C: 结构:创建结构实例时如何分配数组的大小?

c - fscanf 在应该返回 1 的时候始终返回 0

c - 运行时检查失败 #0 : Why am I getting this and what does it mean?

c - 将ASM转换为C

c++ - gdb中链接命令观察执行栈

c - 局部同义变量到非精确类型

c++ - 声明指针的类型?