I don't understand that why the for loop is from 16 to 0.
If int is 16 bit in your OS,
your should set the for loop from 15 to 0,
else if int is 32 bit in your OS,
your should set the for loop from 31 to 0.
so the code is:
int hex2bin (int n)
{
int i,k,mask;
for(i=sizeof(int)*8-1;i>=0;i--)
{
mask = 1<<i;
k = n&mask;
k==0?printf("0"):printf("1");
}
return 0;
}
If you want to display any input(such as "0x10","0x4"),you can declare a function like this:
int hex2bin (const char *str)
{
char *p;
for(p=str+2;*p;p++)
{
int n;
if(*p>='0'&&*p<='9')
{
n=*p-'0';
}
else
{
n=*p-'a'+10;
}
int i,k,mask;
for(i=3;i>=0;i--)
{
mask=1<<i;
k=n&mask;
k==0?printf("0"):printf("1");
}
}
return 0;
}
then ,call hex2bin("0x101") will get the exact binary code of 0x101.