I am given a short int. I need to print the bits of it into two bytes. My code is as follows:
#include <stdio.h>
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",&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 ?
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);
The fields in the union are unsigned, so the use of%d
is an error. Suggest%hu
\$\endgroup\$