用scanf("%x",)可以输入一个十六进制数,用一个char二维数组存放0-15的二进制数串表示。每次循环取余并除以16,把余数对应的二进制串用strcpy存到buf数组里。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 8
int main()
{
void hextoBinary(int num);
int num;
printf("please input an hex datum:" );
scanf("%x",&num);
hextoBinary(num);
return 0;
}
void hextoBinary(int num0)
{
int res,i=0;
char buf[BUFSIZ][5]={"0000"};
char ref[16][5]={"0000","0001","0010","0011",
"0100","0101","0110","0111",
"1000","1001","1010","1011",
"1100","1101","1110","1111"};
while(num0!=0)
{
res=num0%16;
strcpy(buf[i++],ref[res]);
num0=num0/16;
}
//res=num0%16;
//strcpy(buf[i++],ref[res]);
while(i>0)
printf("%s",buf[--i]);
}