通过c语言将16进制转为2进制
时间: 2023-09-15 07:21:05 浏览: 126
以下是将16进制数转换为2进制数的C语言程序:
```c
#include <stdio.h>
int main() {
char hex[17];
long long binary = 0;
int i = 0;
printf("请输入一个16进制数: ");
scanf("%s", hex);
// 将16进制数转换为2进制数
while (hex[i]) {
switch (hex[i]) {
case '0':
binary = binary * 16 + 0; break;
case '1':
binary = binary * 16 + 1; break;
case '2':
binary = binary * 16 + 10; break;
case '3':
binary = binary * 16 + 11; break;
case '4':
binary = binary * 16 + 100; break;
case '5':
binary = binary * 16 + 101; break;
case '6':
binary = binary * 16 + 110; break;
case '7':
binary = binary * 16 + 111; break;
case '8':
binary = binary * 16 + 1000; break;
case '9':
binary = binary * 16 + 1001; break;
case 'A':
case 'a':
binary = binary * 16 + 1010; break;
case 'B':
case 'b':
binary = binary * 16 + 1011; break;
case 'C':
case 'c':
binary = binary * 16 + 1100; break;
case 'D':
case 'd':
binary = binary * 16 + 1101; break;
case 'E':
case 'e':
binary = binary * 16 + 1110; break;
case 'F':
case 'f':
binary = binary * 16 + 1111; break;
default:
printf("非法输入!\n");
return 1;
}
i++;
}
printf("转换为2进制数为: %lld\n", binary);
return 0;
}
```
程序通过 `scanf()` 函数获取一个16进制数,然后通过 `while` 循环将其转换为2进制数。在循环中,我们使用 `switch` 语句将每个16进制数转换为对应的4位2进制数。最后,用 `printf()` 输出结果。
阅读全文