2011-12-27 138 views
1

我需要幫助編寫一個將完整句子轉換爲二進制代碼(ascii - > decimal - > binary)的程序,反之亦然,但我無法做到這一點。現在我正在使用ascii-> binary。將ascii字符十進制值的字符串轉換爲二進制值

ascii字符有十進制值。 a = 97b = 98,等我想獲得一個ASCII字符的十進制值,並將其二進制轉換成dinary或二進制小數,如10(十進制)很簡單:

10 (decimal) == 1010 (binary) 

所以ASCII十進制值a和b是:

97, 98 

這在二進制是(加上空格字符是32,感謝):

11000011000001100010 == "a b" 

11000011100010 == "ab" 

我已經寫此:

int c_to_b(char c) 
{ 
    return (printf("%d", (c ^= 64 ^= 32 ^= 16 ^= 8 ^= 4 ^= 2 ^= 1 ^= 0)); 
} 

int s_to_b(char *s) 
{ 
    long bin_buf = 0; 

    for (int i = 0; s[i] != '\0'; i++) 
    { 
     bin_buf += s[i] ^= 64 ^= 32 ^= 16 ^= 8 ^= 4 ^= 2 ^= 1 ^= 0; 
    } 

    return printf("%d", bin_buf); 
} 

代碼示例

的main.c

int main(void) 
{ 
    // this should print out each binary value for each character in this string 
    // eg: h = 104, e = 101 
    // print decimal to binary 104 and 101 which would be equivalent to: 
    // 11010001100101 
    // s_to_b returns printf so it should print automatically 
    s_to_b("hello, world!"); 
    return 0; 
} 

爲了詳細描述,在for環路在所述第二片段遍歷字符陣列中的每個字符,直至碰到空終止符。每次它計算一個角色時,它都會執行該操作。我正在使用正確的操作嗎?

+0

什麼是「完整的句子轉換成二進制代碼」是什麼意思? – 2011-12-27 06:05:38

+7

您可能需要將其縮小到更具體的範圍。一般來說「不行,爲我做」不是很有成效。 – 2011-12-27 06:06:26

+0

爲什麼你編碼'c^= 64'這意味着'c = c^64'?我不明白,如果它是功課,你的要求是什麼? – 2011-12-27 06:10:59

回答

2

也許你想要的東西,像

void s_to_b(const char*s) 
{ 
    if (s != NULL) { 
    while (*s) { 
     int c = *s; 
     printf(" %d", c); 
     s++; 
    } 
    putc('\n'); 
    } 
} 
+0

是的完全是這樣的,但我相信它打印出十進制字符(它打印值超過1,如9)。有沒有辦法讓字符打印出二進制而不是十進制? – evolon696 2011-12-27 06:48:34

+1

編寫一個函數'print_in_binary'並用'print_in_binary(c)替換printf';' – 2011-12-27 06:57:24

+0

這裏是我想到的: int print_in_binary(char c) int q = c; ((q/2)!= 0)q =(c/2); } printf(「%d」,q); } – evolon696 2011-12-27 07:08:45

相關問題