Vlad Ezikon
Vlad Ezikon

Reputation: 93

How to print a decimal into a 32 binary separating it 8 bits

I am trying to print a 32 binary integer with 8 bits separated by a space. ex (00000000 00000000) Then the result should be used for future testing which I will integrate 512 for example as y.

  #define CHAR_BITS 8

void displayBits(unsigned int n){


int sup = CHAR_BITS*sizeof(int);
while(sup >= 0)
{
    if(n & (((long int)1) << sup) )
        printf("1");
    else
        printf("0");
    sup--;


}
printf("\n");

return;
}

Upvotes: 1

Views: 326

Answers (1)

Govind Parmar
Govind Parmar

Reputation: 21562

If you already have a working loop that prints out a single character at every loop iteration, and i is the loop index, beginning at 0, then the following conditional will add a space every 8 characters:

if(i && ((i + 1) % 8 == 0))
{
    putchar(' ');
}

However, your current code doesn't actually work correctly to produce the binary representation of an int either. Test it with the value 1 for n and examine its output. I see 100000000000000000000000000000001.

Upvotes: 1

Related Questions