我需要帮助编写一个程序,将完整的句子转换为二进制代码(ascii -> 十进制 -> 二进制),反之亦然,但我在做这件事时遇到了麻烦。现在我正在研究 ascii->binary。
ascii 字符具有十进制值。 a = 97
、b = 98
等。我想获取 ascii 字符的十进制值并将其转换为二进制或二进制十进制,例如 10(十进制) ) 在二进制中很简单:
10 (decimal) == 1010 (binary)
所以a和b的ascii十进制值为:
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);
}
代码示例
主.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
循环遍历字符数组中的每个字符,直到遇到空终止符。每次计算一个字符时,它都会执行该操作。我使用的操作是否正确?
最佳答案
也许你想要这样的东西
void s_to_b(const char*s)
{
if (s != NULL) {
while (*s) {
int c = *s;
printf(" %d", c);
s++;
}
putc('\n');
}
}
关于c++ - 将 ascii 字符十进制值的字符串转换为二进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8641666/