用C语言将二进制转换成十进制
时间: 2024-11-09 22:29:12 浏览: 18
在C语言中,将二进制转换为十进制可以使用循环和位操作来实现。以下是一个简单的函数示例:
```c
#include <stdio.h>
#include <math.h>
// Function to convert binary to decimal
int bin_to_dec(int binary) {
int decimal = 0;
int base = 1;
// Iterate through the binary number from right to left (least significant bit)
while (binary > 0) {
int remainder = binary % 10; // Get the remainder after division by 10
decimal += remainder * base; // Add the current digit to the result
binary /= 10; // Shift binary number to the left
base *= 2; // Double the base for each iteration
}
return decimal;
}
int main() {
int binary_num = 101010; // Replace with your binary value
int decimal_num = bin_to_dec(binary_num);
printf("Binary %d is equal to decimal %d\n", binary_num, decimal_num);
阅读全文