user1386132
user1386132

Reputation: 27

converting hex to binary

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.

Upvotes: 0

Views: 5986

Answers (2)

Mazheng
Mazheng

Reputation: 166

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.

Upvotes: 4

MegaNairda
MegaNairda

Reputation: 839

I have already forgotten most of these but try using unsigned instead of int

Upvotes: 0

Related Questions