二进制转十进制,c语言
时间: 2024-10-07 12:06:39 浏览: 58
在C语言中,将二进制数转换为十进制数通常通过循环遍历每一位并累加权重的方式来实现。这里有一个简单的例子:
```c
#include <stdio.h>
#include <math.h>
// Function to convert binary to decimal
int binaryToDecimal(int num) {
int decimal = 0;
int base = 1;
while (num > 0) {
int remainder = num % 10; // Get the last digit of binary number
decimal += remainder * base; // Add the value to decimal with increasing power of 2 for each bit from right to left
base *= 2; // Multiply the base by 2 for next iteration
num /= 10; // Remove the last digit from the binary number
}
return decimal;
}
int main() {
int binaryNum = 1010; // Example binary number
int decimalNum = binaryToDecimal(binaryNum);
printf("Binary %d is equal to Decimal %d\n", binaryNum, decimalNum);
return 0;
}
```
在这个程序中,`binaryToDecimal`函数接收一个二进制数作为输入,逐位提取数字并将其乘以相应的权重(2的幂),最后将结果累加得到十进制值。
阅读全文
相关推荐
















