【问题标题】:Displaying Binary of Each Character in a String显示字符串中每个字符的二进制
【发布时间】:2012-09-23 08:26:02
【问题描述】:

我已经弄清楚如何获取用户的输入(字符串)并从中获取每个字母并给出每个字母的二进制等效项。

问题是我希望每个字母在屏幕上显示时每行一个字母来给出一个二进制数。我需要帮助。

例如:

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

【问题讨论】:

  • 你已经在努力工作了,我看不出你的问题在哪里

标签: c string binary newline


【解决方案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");
    } 

【讨论】:

    【解决方案2】:

    不要立即打印您的10,而是从它们构建一个字符串。然后在刚刚构建的字符串旁边打印出刚刚转换的字符。

    【讨论】:

      【解决方案3】:

      要在新行上打印每个字符,请在打印每个字符后打印一个换行符:

      printf("\n");
      

      要先打印字符,请使用 putchar:

      putchar(c);
      

      【讨论】:

        【解决方案4】:

        抛开不好的代码风格,看来你要找的很简单

        printf("\n");
        

        紧跟在外部 for 循环末尾的 printf("0"); 的语句以添加换行符。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-09-13
          • 2011-07-11
          • 2017-08-26
          • 1970-01-01
          • 2017-03-22
          • 2016-02-26
          • 2015-11-21
          相关资源
          最近更新 更多