输入一个二进制的字符串,编程将其分别转换为十进制、十六进制的数值。用c语言
时间: 2023-02-22 19:40:36 浏览: 107
以下是一个示例代码,它将二进制字符串转换为十进制和十六进制:
```c
#include <stdio.h>
#include <math.h>
#include <string.h>
int binaryToDecimal(char binary[]) {
int decimal = 0, length = strlen(binary), power = 0;
for (int i = length - 1; i >= 0; i--) {
if (binary[i] == '1') {
decimal += pow(2, power);
}
power++;
}
return decimal;
}
void binaryToHexadecimal(char binary[]) {
int length = strlen(binary), remainder, decimal = binaryToDecimal(binary);
char hexadecimal[100];
int i = 0;
while (decimal != 0) {
remainder = decimal % 16;
if (remainder < 10) {
hexadecimal[i] = 48 + remainder;
i++;
} else {
hexadecimal[i] = 55 + remainder;
i++;
}
decimal /= 16;
}
printf("十进制: %d\n", binaryToDecimal(binary));
printf("十六进制: ");
for (int j = i - 1; j >= 0; j--) {
printf("%c", hexadecimal[j]);
}
printf("\n");
}
int main() {
char binary[100];
printf("请输入一个二进制字符串: ");
scanf("%s", binary);
binaryToHexadecimal(binary);
return 0;
}
```
阅读全文