3kings 3kings - 3 months ago 13
C Question

Converting Ascii to binary in C

So here is my code

void ascToBinary(int character, int *ones)
{
if(character == 1)
{
printf("1");
*ones+=1;
return;
}
else
{
if((character%2) == 0)
{
printf("0");
character = character/2;
}
else
{
printf("1");
character = character/2;
*ones+=1;

}
binaryPrinter(character, ones);
}
}


Can anyone try to help me out on where something is wrong here. It compiles fine and does some ascii letters correct. If you try an 'e' though it will print out '1010011' instead of the correct binary.

All help appreciated Thanks Guys.

Answer

You print the results in the wrong order. The correct output is '1100101'. You can flip it like this:

    void ascToBinary(int character, int *ones)
    {
        if(character == 1)
        {
           printf("1");
           *ones+=1;
           return;
        }
        else
        {
            char out;
            if((character%2) == 0)
            {
                 out = '0';
                 character = character/2;
            }
            else
            {
                 out = '1';
                 character = character/2;
                 *ones+=1;

            }
            ascToBinary(character, ones);
            putchar (out);
        }
    }
Comments