$0.06

Print String Without 0 At The End

Ask a question+
9

I am trying to print the string “Hello” in binary.

Here is my code:

char str[] = "Hello";
for (int j = 0; j < sizeof(str); j++)
{
    unsigned char ch = str[j];
    for (int i = 7; i >= 0; i--) {
        printf("%d", (c >> i) & 1 ? 1 : 0);
    }
    printf(" ");
}

The result is
01001000 01100101 01101100 01101100 01101111 00000000
instead of
01001000 01100101 01101100 01101100 01101111

add comment

1 Answer

3

You can modify your loop condition as:
for (int j = 0; str[j] != '\0'; j++)
Currently, your loop for all characters in str[] that even include the trailing null character. With the modified condition, you exit the loop on seeing the null character responsible for trailing 0.

| H | e  |  l  |  l | o | \0 |

  T   T   T   T   T   F   str[i] != '\0'

sizeof(t) = 6
strlen(t) = 5
Tamara Mirzoyan 130
1

Awesome, thank you!!

Vahe Minasyan
add comment

Your Answer