c - 显示字符串中每个字符的二进制

标签 c string binary newline

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

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

例如:

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

最佳答案

您只需在处理每个字符后添加一个 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");
    } 

关于c - 显示字符串中每个字符的二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12550808/

相关文章:

java - Android 上如何从字符串中获取 URL

c - 想知道如何 "reveal"一个 "hidden"字符串(格式如 ****)

C# 合并运算符抛出

architecture - 将 CLI 工具拆分为多个可执行文件有什么好处

c++ - 当模态对话框处于事件状态时检测主应用程序窗口上的 WM_CLOSE 事件?

c - 在 C 中计算 csv 和 txt 文件之间的行数时出现问题

binary - 如何解码这个二进制消息?

r - 更快的替代 `range(which(..))`

c - dsPIC33EP512MU810 ADC channel 到引脚的映射

c - 可移植的获取时间的方式