# How can I change a char to a binary!

With C langluage, I have a char, I want change it to a binary?
for example, char'0', change to binary is 11000.
how can I do it?
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Commented:
On other systems you would use the itoa() function, which allows you to convert an integer to an ASCII string by specifying thebase or radix (in your case, this would be 2 for binary). This is usually used to convert an integer to a base 10 (decimal) string, but can use anything from 2 to 36.

This page contains several methods to create your own atoi() function. If you search for a2i on this page, you will find the one that I would use:
http://dbforums.com/archives/t57204.html

Once you have this itoa() function, you would then call it like this:

char c = '0';
char outString[1024];

itoa((int) c, outString, 2);

To convert the character '0' to it's binary representation.
Commented:
use strtol

long int strtol(const char *nptr, char **endptr, int base);

result = strtol ( start, NULL, 2 );

man strtol ...
Commented:
#include <stdio.h>

char *int2bin( int aint, int width )
{
char *buf;
int j;
int i = width;

// room for a null
buf = (char *)calloc(1, width+1);
memset(buf,'0',width);

while ( 1 )
{
j = aint % 2;
aint /= 2;

buf[i--] = j == 0 ? '0' : '1';

if (aint == 0 || i == 0)
break;
}
return buf;
}

int main( int argc, char **argv )
{
char achar;

achar = 'z';

printf("%s\n",int2bin(achar,16));
return 0;
}

// this returns 00000000001111010
// mainly this is just to show that all you do is divide by 2 until you reach zero, and reverse the order that you
// recieved the remainders in

// just as easily you could change the base number to 8, for octal, but for 16, you would need some lookup table
// for the A,B,C,D,E,F values

Experts Exchange Solution brought to you by