我想到的一个简单程序是将十六进制数转换为二进制数,然后使用计数器对零和一的数目进行计数。
最佳答案
#include <stdio.h>
#define MAX 1000
int main()
{
char binarynum[MAX], hexa[MAX];
long int i = 0,number_of_zeros=0,number_of_ones=0;
printf("Enter the value for hexadecimal ");
scanf("%s", hexa);
printf("\n Equivalent binary value: ");
while(hexa[i])
{
switch (hexa[i])
{
case '0':
printf("0000");
number_of_zeros +=4;
break;
case '1':
printf("0001");
number_of_zeros +=3;
number_of_ones +=1;
break;
case '2':
printf("0010");
number_of_zeros +=3;
number_of_ones +=1;
break;
case '3':
printf("0011");
number_of_zeros +=2;
number_of_ones +=2;
break;
case '4':
printf("0100");
number_of_zeros +=3;
number_of_ones +=1;
break;
case '5':
printf("0101");
number_of_zeros +=2;
number_of_ones +=2;
break;
case '6':
printf("0110");
number_of_zeros +=2;
number_of_ones +=2;
break;
case '7':
printf("0111");
number_of_zeros +=1;
number_of_ones +=3;
break;
case '8':
printf("1000");
number_of_zeros +=3;
number_of_ones +=1;
break;
case '9':
printf("1001");
number_of_zeros +=2;
number_of_ones +=2;
break;
case 'A': case 'a':
printf("1010");
number_of_zeros +=2;
number_of_ones +=2;
break;
case 'B': case 'b':
printf("1011");
number_of_zeros +=1;
number_of_ones +=3;
break;
case 'C': case 'c':
printf("1100");
number_of_zeros +=2;
number_of_ones +=2;
break;
case 'D': case 'd':
printf("1101");
number_of_zeros +=1;
number_of_ones +=3;
break;
case 'E': case 'e':
printf("1110");
number_of_zeros +=1;
number_of_ones +=3;
break;
case 'F': case 'f':
printf("1111");
number_of_ones +=4;
break;
default:
printf("\n Invalid hexa digit %c ", hexa[i]);
return 0;
}
i++;
}
printf("\nNumber of zero\'s is %d\n",number_of_zeros);
printf("Number of One\'s is %d\n",number_of_ones);
return 0;
}
关于c - 如何将16位十六进制数转换为二进制数,然后计算零和一的个数?使用最简单的C程序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48727834/