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

why does it doesn't give an answer?

Page 1 of 1

2 Replies - 14690 Views - Last Post: 31 August 2007 - 11:40 PM Rate Topic: -----

#1 arem026  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • 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("HEXADECIMAL TO BINARY\n");
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  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 19
  • View blog
  • 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

Was This Post Helpful? 0
  • +
  • -

#3 born2c0de  Icon User is offline

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

Reputation: 180
  • View blog
  • Posts: 4,667
  • 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.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1