将字符串的ASCII字符十进制值转换为二进制值

converting string of ascii character decimal values to binary values

本文关键字:转换 二进制 十进制 字符 字符串 ASCII      更新时间:2023-10-16

我需要帮助编写一个将完整句子转换为二进制代码(ascii ->十进制->二进制)的程序,反之亦然,但我在做这件事时遇到了麻烦。现在我正在处理ascii->二进制。

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] != ''; 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');
  }
}