# Hexadecimal to Binary in C.. what's wrong?

Page 1 of 1

## 2 Replies - 15173 Views - Last Post: 31 August 2007 - 11:40 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=32489&amp;s=86234de8bc20e6182cc705c7bc8b7bf8&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 arem026

• New D.I.C Head

Reputation: 1
• Posts: 22
• Joined: 28-August 07

# Hexadecimal to Binary in C.. what's wrong?

Posted 30 August 2007 - 08:37 PM

hey guys help me why does tihs program that will convert hexa to binary doesn't give an answer what's wrong in here:
{
int i;
char s[20];
clrscr();
printf("Enter A Hexadecimal Number:");
scanf("%s",s);
gets(s);
printf("Binary= ");
for(i=0;s[i]!=NULL;i++)
{
switch(s[i])
{
case '0':
printf("0000");
break;
case '1':
printf("0001");
break;
case '2':
printf("0010");
break;
case '3':
printf("0011");
break;
case '4':
printf("0100");
break;
case '5':
printf("0101");
break;
case '6':
printf("0110");
break;
case '7':
printf("0111");
break;
case '8':
printf("1000");
break;
case '9':
printf("1001");
break;
case 'a':
case 'A':
printf("1010");
break;
case 'b':
case 'B':
printf("1011");
break;
case 'c':
case 'C':
printf("1100");
break;
case 'd':
case 'D':
printf("1101");
break;
case 'e':
case 'E':
printf("1110");
break;
case 'f':
case 'F':
printf("1111");
break;
default:
printf("Number Is Not Hexadecimal");
break;
}
}
}

Is This A Good Question/Topic? 1

## Replies To: Hexadecimal to Binary in C.. what's wrong?

### #2 Xing

Reputation: 19
• Posts: 725
• Joined: 22-July 06

## Re: Hexadecimal to Binary in C.. what's wrong?

Posted 30 August 2007 - 09:26 PM

Post at least one complete compilation unit with code tags.

This post has been edited by Xing: 30 August 2007 - 09:26 PM

### #3 born2c0de

• printf("I'm a %XR",195936478);

Reputation: 184
• Posts: 4,673
• Joined: 26-November 04

## Re: Hexadecimal to Binary in C.. what's wrong?

Posted 31 August 2007 - 11:40 PM

scanf("%s",s);
gets(s);

You are trying to take input twice.
As a result, after the first Hex Number is entered, the gets() function does not take input but sets the first element in the buffer (in this case s[0]) to 0. Hence the String is considered empty since the '\0' character is the 0th element in the character array.

Remove either the gets() or scanf() function and the code will work as expected.