1

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;
}
Vlad Ezikon
  • 93
  • 2
  • 11
  • Can you try and rephrase the question? That doesn't really convey what you're trying to do. Maybe express in terms of desired output. – tadman Feb 08 '19 at 02:07
  • my code what it does it prints 32binary like 00000000000000000000000.... instead i want it to be printed with spaces every eight 0's – Vlad Ezikon Feb 08 '19 at 02:43
  • 1
    If code needs to "print a 32 binary integer" than use `(u)int32_t` rather than `int` and avoiding _assuming_ `int` is 32-bit. – chux - Reinstate Monica Feb 08 '19 at 02:43
  • regarding: `if(n & (((long int)1) << sup) )` this has the potental to result in undefined behavior. when shifting a 1, use `unsigned int' or `long unsigned int`, not `long int` – user3629249 Feb 10 '19 at 07:18

1 Answers1

1

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.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85