将16进制数转换为2进制c语言
时间: 2023-12-27 22:05:14 浏览: 76
c语言中十六进制转二进制显示的实现方法
以下是将16进制数转换为2进制的c语言代码:
```c
#include <stdio.h>
int main()
{
char hex[17];
long long bin, place;
int i = 0, rem, val;
printf("请输入一个16进制数: ");
scanf("%s", hex);
bin = 0ll;
place = 0ll;
// 将每个16进制数位转换为2进制
for (i = 0; hex[i] != '\0'; i++)
{
bin = bin * place;
switch (hex[i])
{
case '0':
val = 0;
break;
case '1':
val = 1;
break;
case '2':
val = 2;
break;
case '3':
val = 3;
break;
case '4':
val = 4;
break;
case '5':
val = 5;
break;
case '6':
val = 6;
break;
case '7':
val = 7;
break;
case '8':
val = 8;
break;
case '9':
val = 9;
break;
case 'a':
case 'A':
val = 10;
break;
case 'b':
case 'B':
val = 11;
break;
case 'c':
case 'C':
val = 12;
break;
case 'd':
case 'D':
val = 13;
break;
case 'e':
case 'E':
val = 14;
break;
case 'f':
case 'F':
val = 15;
break;
default:
printf("无效的输入\n");
return 1;
}
bin += val;
place = 10ll;
}
// 将2进制数转换为16进制
i = 0;
while (bin != 0)
{
rem = bin % 2;
bin /= 2;
hex[i] = rem == 0 ? '0' : '1';
i++;
}
hex[i] = '\0';
// 输出2进制数
printf("2进制数为: ");
for (i = i - 1; i >= 0; i--)
printf("%c", hex[i]);
printf("\n");
return 0;
}
```
该程序接受用户输入一个16进制数,并将其转换为2进制数。
阅读全文