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

时间:2011-12-27 06:04:13

标签: c++ c binary

我需要帮助编写一个程序,将完整的句子转换为二进制代码(ascii - > decimal - > binary),反之亦然,但我无法做到这一点。现在我正在研究ascii->二进制文件。

ascii字符具有十进制值。 a = 97b = 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);
}

代码示例

的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循环遍历字符数组中的每个字符,直到它到达空终止符。每次计算一个角色时,它都会进行该操作。我使用正确的操作吗?

1 个答案:

答案 0 :(得分:2)

也许你想要像

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