int hex2bin (int n)
{
int i,k,mask;
for(i=16;i>=0;i--)
{
mask = 1<<i;
k = n&mask;
k==0?printf("0"):printf("1");
}
return 0;
}
I need this to work for any hex i give as an input. Meaning hex2bin(0x101) and hex2bin(0x04) should print out their respective binary numbers.
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:
If you want to display any input(such as “0x10″,”0x4”),you can declare a function like this:
then ,call hex2bin(“0x101”) will get the exact binary code of 0x101.