C add spacing in between binary numbers

Viewed 120

I'm looking for a way to add spacing for binary numbers after every 4th digit. My problem is I have an extra digit at the MSB when there shouldn't be.

MY output

Enter a number to convert to binary: 1
Enter a number to convert to binary: 8
Enter a number to convert to binary: 0

0 0000 0000 0000 0001
0 0000 0000 0000 1000
0 0000 0000 0000 0000

Expected output:

Enter a number to convert to binary: 1
Enter a number to convert to binary: 8
Enter a number to convert to binary: 0

0000 0000 0000 0001
0000 0000 0000 1000
0000 0000 0000 0000

My program:

#include <stdio.h>
#include <stdlib.h>
void convert(int num){
    int bit,i;
    for ( i = 16; i >= 0; i--)
    {
        bit = num>>i;
        if (bit & 1)
            printf("1");
        else
            printf("0");

        if (i && !(i & 3)) // if i is a multiple of 4
            printf(" ");
    }
    printf("\n");
}
1 Answers

The for-loop iterates once too many. It starts at i = 16 and ends when i = -1, thus it loops 17 times instead of 16.

Initializing i at 15 produces the intended result:

for ( i = 15; i >= 0; i--)
Related