0
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.

Mayur Birari
  • 5,837
  • 8
  • 34
  • 61
user1386132
  • 37
  • 2
  • 8
  • 2
    Please don't prefix your titles with "C -" and such. That's what the tags are for. – John Saunders May 10 '12 at 06:11
  • Here's an equivalent function written in Java: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7-b147/java/lang/Integer.java#Integer.toBinaryString%28int%29 – Greg Kopff May 10 '12 at 06:12
  • Your correct output (12 bits) seems wrong to me. If you only need 12 bits, change i=16 to 1=12 – kgiannakakis May 10 '12 at 06:14
  • I suppose this is some sort of homework? Therefore just some hint. If you want to skip the initial zeroes in the output, just have a loop before the current one that checks if the value `k` is `0`. – Jens Gustedt May 10 '12 at 06:20
  • I'm trying to write a function that would work for any input. if i call `hex2bin(0x101)` and `hex2bin(0x4)` they should each output the correct binary number. – user1386132 May 10 '12 at 06:23
  • possible duplicate of [Convert Hex to Binary in C](http://stackoverflow.com/questions/8205298/convert-hex-to-binary-in-c) – Caleb May 10 '12 at 06:35
  • @user1386132 As your approach is fine, though limited to 16 bits. What problem do you have with your current code ? What does it output ? What should it output ? – nos May 10 '12 at 06:38

2 Answers2

4

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.

Mazheng
  • 166
  • 4
  • normally I would be calling the function with an integer as a parameter. is there a way to cast the int as a char* to pass it in as an argument for hex2bin? – user1386132 May 10 '12 at 10:30
  • If your parameter is integer,just use the first code.Call the first hex2bin,have a try,it is ok. – Mazheng May 10 '12 at 10:55
0

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

MegaNairda
  • 829
  • 2
  • 14
  • 24