2012-09-23 72 views
0

我已經想出瞭如何獲取用戶的輸入(字符串)並從它們中取出每個字母並給出每個字母的二進制等值。在字符串中顯示每個字符的二進制碼

問題是我希望每個字母在屏幕上顯示時每行有一個字母給出一個二進制數字。我想這樣做的幫助。

例如:

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

你已經在做所有的努力了,我沒有看到你的問題在哪裏 – Asciiom

回答

0

而不是打印您10立即,建立從他們的字符串。然後打印剛剛構建的字符串旁邊的字符。

0

要在新行打印每一個字符,打印每個字符後打印一個換行符:

printf("\n"); 

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

putchar(c); 
0

撇開糟糕的代碼風格,似乎你正在尋找的是一個簡單的

printf("\n"); 

陳述緊接在printf("0");在for循環的最後添加換行符。

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"); 
    } 
相關問題