# Thread: In need of guidance

1. ## In need of guidance

I am currently working on a program to convert a character to binary and binary back to a character. This is an assignment for school. I have the first part done and I do understand the function for converting the ASCII into binary. What I am having problems with is the function for converting the binary back into ACSII. I have looked around on the net for examples but for some reason I am not grasping the code.

Where/how should I look for an explanation on how a function like that should work.

2. I have posted many.... so to be nice I will just go find one for you.

3. Have you tried searching the forums for what you need?

4. Code:
``` void int16tobstr(short x, char s[17])
{
int bit;

for(bit = 0; bit < 16; ++bit)
*s++ = '0' + !!(x & (1 << bit));
*s = 0;
}```

So with this function s[17] is the array for the binary number. so is *s++ used to check the numbers in the array against the 0 + !!(x &(1<<bit)). so roughly how does it work??

but thanks for the function.

5. Ok lets make it a little more generalized

Example:
Code:
```#include <limits.h>

char *longtobstr(long x)
{
int bit;
char *s = malloc(LONG_BIT + 1);

if(!s)
return 0;

s[LONG_BIT] = '\0'; /* Terminate the string. */

for(bit = 0; bit < LONG_BIT; ++bit)
s[LONG_BIT - bit] = '0' + !!(x & (1 << bit));

return s;
}```
Clearer?

6. so I tried the longtobstr functions and I get an LONG_BIT error for being undefined. I have a feeling that my head is fully of jellie right now and I am missing something pitifully simple.

7. I wouldn't call that a good example of how to write such a function.

--
Mats

8. Maybe not, but at least it can't be used for homework.

1) Make sure the array size is equal to CHAR_BIT. If not, make adjustments or bail out.
2) The rightmost digit (array[ CHAR_BIT - 1 ]) is least significant, so the mapping with bit positions is reversed. Alternately, you can reverse the string to take advantage of the more natural mapping. Either way, 1 << index corresponds to array[ index ].
3) Use X |= Y to enable a bit, X &= ~Y to clear one (assuming X is initialized to zero, the latter probably won't be necessary).