打印字符串,结尾无填充0

时间:2019-06-25 05:36:30

标签: c bit-manipulation c-strings

我正在尝试以二进制形式打印字符串"Hello"

我可以使用它,但是,我希望它在打印时不带末尾的填充

如此

  01001000 01100101 01101100 01101100 01101111

代替

  01001000 01100101 01101100 01101100 01101111 00000000

这是我的代码:

char t[] = "Hello";

for (int j = 0; j < sizeof(t); j++)
{
    unsigned char c = t[j];

    for (int i = 7; i >= 0; i--) {
        printf("%d", (c >> i) & 1 ? 1 : 0);
    }

    printf(" ");

}

4 个答案:

答案 0 :(得分:8)

您可以将循环条件修改为:

for (int j = 0; t[j] != '\0'; j++)
/*              ^^^^^^^^^^^^     */

当前,您循环搜索t[]中的所有字符,甚至包括结尾的nul字符。修改条件后,您会退出循环,看到nul字符负责尾随零。

+---+---+---+---+---+---+
| H | e | l | l | o |\0 |
+---+---+---+---+---+---+
  T   T   T   T   T   F   t[i] != '\0'

sizeof(t) = 6
strlen(t) = 5

答案 1 :(得分:3)

或者只是:

 for (int j = 0; j < (sizeof(t)-1); j++)

避免打印结尾字符nul

答案 2 :(得分:2)

从逻辑上讲,您应该这样做:

for (int j = 0; j < sizeof(t) - 1; j++)

当您执行sizeof(t)时,字符串末尾的空字符也将被计数并因此被打印。

另一种解决方法是:

for (int j = 0; t[j] != '\0'; j++)

答案 3 :(得分:0)

j < sizeof(t);循环循环字符数加一个(空字符)次。代替此旋转循环,直到\0字符不出现为止。对于例如

for (int j = 0; t[j]; j++) { }

示例工作代码

char t[] = "Hello";
for (int j = 0; t[j] != '\0'; j++) /* using t[j]!='\0'  is much quicker than using strlen(t) */
{
    unsigned char c = t[j];
    for (int i = 7; i >= 0; i--) {
        printf("%d", (c >> i) & 1); /* No need to use ternary operator */
    }
    printf(" ");
}

找到有关在strlen()循环条件下不使用for的好读物:Is using strlen() in the loop condition slower than just checking for the null character?

相关问题