0

I have figured out how to get user's input (string) and take each letter from them and give a binary equivalent of each letter.

The problem is I want each letter to give a binary number by having one letter per line when displaying on screen. I would like help in doing so.

For example:

C 0 1 0 0 0 0 1 1
h 0 1 1 0 1 0 0 0
a 0 1 1 0 0 0 0 1
n 0 1 1 0 1 1 1 0
g 0 1 1 0 0 1 1 1

This is the code I used:

#include <stdio.h>

int main()
{

    //get input
    printf( "Enter a string: " );
    char s[255];
    scanf( "%[^\n]s" , s );

    //print output 
    printf( "'%s' converted to binary is: " , s );

    //for each character, print it's binary aoutput
    int i,c,power;

    for( i=0 ; s[i]!='\0' ; i++ )
    {
        //c holds the character being converted
        c = s[i];

        //for each binary value below 256 (because ascii values < 256)
        for( power=7 ; power+1 ; power-- )
        //if c is greater than or equal to it, it is a 1
        if( c >= (1<<power) )
        {
            c -= (1<<power); //subtract that binary value
            printf("1");
        }
        //otherwise, it is a zero
        else
            printf("0");
    } 

    return 0;
}
1
  • You're doing all the hard work already, I don't see where your problem is Commented Sep 23, 2012 at 8:32

4 Answers 4

1

You just need to add a printf("\n") statement after you process each character.

for( i=0 ; s[i]!='\0' ; i++ )
    {
        //c holds the character being converted
        c = s[i];

        //for each binary value below 256 (because ascii values < 256)
        for( power=7 ; power+1 ; power-- )
        //if c is greater than or equal to it, it is a 1
        if( c >= (1<<power) )
        {
            c -= (1<<power); //subtract that binary value
            printf("1");
        }
        //otherwise, it is a zero
        else
            printf("0");

        /* Add the following statement, for this to work as you expected */
        printf("\n");
    } 
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of printing your 1and 0immediately, build a string from them. Then print out the character you just converted next to the string you just built.

Comments

0

To print each character on a new line, print a newline after printing each character:

printf("\n");

To print the character first, use putchar:

putchar(c);

Comments

0

Setting aside the bad code style, it seems what you are looking for is a simple

printf("\n");

statement immediately following the printf("0"); in the end of the outer for loop to add newlines.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.