# Help Needed...

This is a discussion on Help Needed... within the C Programming forums, part of the General Programming Boards category; I hope someone can help me out on this, I've pretty much been driven to desperation. I've been on c ...

1. ## Help Needed...

I hope someone can help me out on this, I've pretty much been driven to desperation. I've been on c for only a few weeks, and this is the only bump I've come across, and it's driving me nuts. I've been using various webpages as guides, mainly...

I'm trying to write a simple prog to convert a Hexadecimal number to a binary string. I used stdio and string libraries, and declared 2 char arrays (a & c). From what I know about Hexa -> binary conversion, each Hexa digit represents four binary digits. 8 -> 1000, 2 -> 0010, etc.

So I basically did this:

Code:
```#include <stdio.h>
#include <string.h>

int main (void)

{

char a[100];
int b;
char c[100];
int d = 0;
int e = 1;
int f = 2;
int h = 3;

scanf ("%s", a);

for (b = 0; b < strlen(a); b = b + 1){

if (a[b] == '0'){
c[d] = '0';
c[e] = '0';
c[f] = '0';
c[h] = '0';
d = d + 4;
e = e + 4;
f = f + 4;
h = h + 4;
}

}

printf ("%s", c);

return 0;

}```
I have 15 more of those if blocks, one for each other Hexa digit. Yeah, I know its kinda awkward and primitive...but its the best I can do. The answer DOES come out...the binary bit...but its followed by a string of garbage, and I have no idea how to get rid of it.

Can anyone help? Please? I can't figure out what's wrong... Thanks.

...oh, and can anyone make suggestions on good c books to read?

2. printf ("%s", c);

%s assumes a '\0' terminated string. You just need to put '\0' at the end of string c.

Code:
```for (b = 0; b < strlen(a); b = b + 1)
{
....
}
c[b] = '\0';```
This assumes that string c is big enough to hold the additional '\0'.

3. ## Can you!!

Can you give one input and tell me what output do you want. I am not able to get you. Moreover code is confusing adding 4 something...........Please use comments.
Saravanan.

4. Using your technique, you might want to do something like:
Code:
```i=0;
for (i = 0; i < strlen(a); i++)
{
switch (a[i])
{
case '0':
strcat(c, "0000");
break;
...
case 'F':
case 'f':
strcat(c, "1111");
break;
}```
There are of course many other ways to accomplish your task, this one will work but many more ways are better. Once you get this one working, try thinking it through again and figure out another way.

5. Thanks a lot! ...finally got it workin'.

Walt: I haven't thought of using Case for this... thanks for the advice. I'll look up strcat...