user11402812
user11402812

Reputation:

Print String Without Padded 0 At The End

I am trying to print the string "Hello" in binary.

I get it to work, however, I would like it to print without the padded at the end

so

  01001000 01100101 01101100 01101100 01101111

instead of

  01001000 01100101 01101100 01101100 01101111 00000000

Here is my code:

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(" ");

}

Upvotes: 3

Views: 863

Answers (4)

Achal
Achal

Reputation: 11921

This j < sizeof(t); rotates loop number of character plus one more(nul character) times). Instead of this rotate loop until \0 character not occur. For e.g

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

Sample working code

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(" ");
}

Find a good read regarding not to use strlen() in for loop condition : Is using strlen() in the loop condition slower than just checking for the null character?

Upvotes: 0

Nick
Nick

Reputation: 515

Logically, you should just do:

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

When you do sizeof(t) the null character at the end of the string is also counted and therefore printed.

Another fix would be:

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

Upvotes: 2

Gyapti Jain
Gyapti Jain

Reputation: 4106

You can modify your loop condition as:

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

Currently you loop for all characters in t[] that even include the trailing nul character. With modified condition you exit the loop on seeing the nul character responsible for trailing zeros.

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

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

Upvotes: 8

Mike
Mike

Reputation: 4288

Or just:

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

to avoid printing the trailing character nul.

Upvotes: 3

Related Questions