我需要幫助編寫一個將完整句子轉換爲二進制代碼(ascii - > decimal - > binary)的程序,反之亦然,但我無法做到這一點。現在我正在使用ascii-> binary。將ascii字符十進制值的字符串轉換爲二進制值
ascii字符有十進制值。 a = 97
,b = 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
環路在所述第二片段遍歷字符陣列中的每個字符,直至碰到空終止符。每次它計算一個角色時,它都會執行該操作。我正在使用正確的操作嗎?
什麼是「完整的句子轉換成二進制代碼」是什麼意思? – 2011-12-27 06:05:38
您可能需要將其縮小到更具體的範圍。一般來說「不行,爲我做」不是很有成效。 – 2011-12-27 06:06:26
爲什麼你編碼'c^= 64'這意味着'c = c^64'?我不明白,如果它是功課,你的要求是什麼? – 2011-12-27 06:10:59