3

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

}
Gyapti Jain
  • 4,056
  • 20
  • 40

4 Answers4

8

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
Gyapti Jain
  • 4,056
  • 20
  • 40
3

Or just:

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

to avoid printing the trailing character nul.

Mike
  • 4,041
  • 6
  • 20
  • 37
2

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++)
Nick
  • 463
  • 4
  • 13
  • 2
    in the second option, strlen() is executed again and again in the loop. You should avoid such a behavior. – eyalm Jun 25 '19 at 05:57
0

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?

Achal
  • 11,821
  • 2
  • 15
  • 37