c语言输入一个二进制数,将其转化为十进制数和十六进制数再输出
时间: 2024-11-06 19:18:49 浏览: 27
在C语言中,将二进制数转换为十进制和十六进制通常需要用户手动输入,然后通过循环和位操作来进行计算。下面是一个简单的示例程序,演示了如何实现这个功能:
```c
#include <stdio.h>
#include <string.h>
// Function to convert binary to decimal
int binaryToDecimal(char *binary) {
int decimal = 0;
int base = 1;
int len = strlen(binary);
for (int i = len - 1; i >= 0; i--) {
if (binary[i] == '1') {
decimal += base;
}
base *= 2;
}
return decimal;
}
// Function to convert decimal to hexadecimal
char* decimalToHexadecimal(int decimal) {
char hex[17]; // Assuming a maximum of 16 digits in hexadecimal
memset(hex, '0', sizeof(hex));
int index = 0;
while (decimal != 0) {
hex[index++] = (decimal % 16) + '0';
if (hex[index - 1] > '9') {
hex[index++] = 'A' - ('0' - (hex[index - 1] - '0'));
}
decimal /= 16;
}
hex[--index] = '\0'; // NULL terminate the string
reverse(hex); // Reversing the string since we start from right
return hex;
}
void reverse(char str[]) {
int left = 0, right = strlen(str) - 1;
while (left < right) {
std::swap(str[left], str[right]);
left++;
right--;
}
}
int main() {
char binary[32];
printf("Enter a binary number: ");
scanf("%s", binary);
int decimal_num = binaryToDecimal(binary);
printf("Decimal representation: %d\n", decimal_num);
char hex_num[17];
strcpy(hex_num, decimalToHexadecimal(decimal_num));
printf("Hexadecimal representation: %s\n", hex_num);
return 0;
}
```
阅读全文