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.

7
  • 2
    Please don't prefix your titles with "C -" and such. That's what the tags are for. Commented May 10, 2012 at 6:11
  • Here's an equivalent function written in Java: grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/… Commented May 10, 2012 at 6:12
  • Your correct output (12 bits) seems wrong to me. If you only need 12 bits, change i=16 to 1=12 Commented May 10, 2012 at 6: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. Commented May 10, 2012 at 6: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. Commented May 10, 2012 at 6:23

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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?
If your parameter is integer,just use the first code.Call the first hex2bin,have a try,it is ok.
0

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

1 Comment

Nice advice, but that only makes a difference if the number involved is negative.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.