Printing the bits of an integer using bitfields and union I am given a short int. I need to print the bits of it into two bytes. My code is as follows:

#include &lt;stdio.h&gt;

union info{
    short z;
    struct data{
        unsigned a:1;
        unsigned b:1;
        unsigned c:1;
        unsigned d:1;
        unsigned e:1;
        unsigned f:1;
        unsigned g:1;
        unsigned h:1;
  };
}t;

union byte{
short n;
struct inside{
    char p:8;
    char q:8;
  };
}v;

int main(void)
{
 short x;

 scanf("%hd",&amp;x);

 v.n=x;

 t.z=v.q;

 printf("%d %d %d %d %d %d %d %d\n",t.h,t.g,t.f,t.e,t.d,t.c,t.b,t.a);

 t.z=v.p;

 printf("%d %d %d %d %d %d %d %d",t.h,t.g,t.f,t.e,t.d,t.c,t.b,t.a);

 return 0;
}


My code gives the correct result. But I think that I've written an unnecessarily long code. Moreover, for larger bytes ( like in case of int ) , the process seems to be tiresome. Can I write the code in a simpler way ?
Avoid global variables - there's no need for t and v to exist outside main().

Always check the return value of scanf() before using the written values.

Don't assume that CHAR_BIT is 8, or that sizeof (short) is 2.  Neither of those is portable.

Don't assume a particular ordering of bit fields within a struct - that's entirely compiler-dependent.

Portable code needs a loop to print the bits, like this:

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;

int main(void)
{
    short x;
    if (scanf("%hi", &amp;x) != 1) {
        fputs("Input error\n", stderr);
        return EXIT_FAILURE;
    }

    unsigned short v = (unsigned short)x;

    unsigned short mask = -1u;                /* 11111... */
    mask -= (unsigned short)(mask / 2);       /* 10000... */

    while (mask) {
        printf("%d ", (v &amp; mask) != 0);
        mask &gt;&gt;= 1;
    }
    printf("\n");
}