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