0

ユーザーの入力(文字列)を取得し、それらから各文字を取得して、各文字に相当するバイナリを与える方法を理解しました。

問題は、画面に表示するときに 1 行に 1 文字ずつ、各文字に 2 進数を与えることです。その際に助けていただきたいと思います。

例えば:

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

これは私が使用したコードです:

#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;
}
4

4 に答える 4

1

printf("\n")各文字を処理した後、ステートメントを追加するだけです。

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");
    } 
于 2012-09-23T09:31:47.587 に答える
0

1and を0すぐに印刷する代わりに、それらから文字列を作成します。次に、作成したばかりの文字列の横に、変換したばかりの文字を出力します。

于 2012-09-23T08:33:57.027 に答える
0

各文字を新しい行に出力するには、各文字を出力した後に改行を出力します。

printf("\n");

最初に文字を出力するには、putchar を使用します。

putchar(c);
于 2012-09-23T08:34:46.373 に答える
0

悪いコード スタイルはさておき、探しているのは単純なようです。

printf("\n");

printf("0");外側の for ループの最後にある の直後のステートメントで改行を追加します。

于 2012-09-23T08:35:22.180 に答える