accessing bit fields in structure
c
Solution
If you intend to access the same data as multiple data-types, then you need to use an `union` in C. Take a look at the following snippet that will
- Write to a union treating it as a 32bit integer (and then)
- Access the data back as 4 individual 8bit bit-fields (and also for good measure)
- Access the same data back again as a 32bit integer
#include<stdio.h>
typedef struct {
unsigned long a:8;
unsigned long b:8;
unsigned long c:8;
unsigned long d:8;
}bitfields;
union data{
unsigned long i;
bitfields bf;
};
int main()
{
union data x;
unsigned long v = 0xaabbccdd;
printf("sizeof x is %dbytes\n",sizeof(x));
/* write to the union treating it as a single integer */
x.i = v;
/* read from the union treating it as a bitfields structure */
printf("%x %x %x %x\n", x.bf.a, x.bf.b, x.bf.c, x.bf.d);
/* read from the union treating it as an integer */
printf("0x%x\n", x.i);
return 0;
}
Note that when union is accessed as an integer, the endian-ness of the system determines the order of the individual bit-fields. Hence the above program on a 32bit x86 PC (little-endian) will output :
sizeof x is 4bytes
dd cc bb aa
0xaabbccdd
Problem
I am new to the bit fields concept. I am trying to access the elements in the structure, but it is showing the error at `aa=v` like this. ``` error: incompatible types when assigning to type ‘cc’ from type ‘long unsigned int ’ ``` And it is showing error if I typecasted at `aa= (cc)v;` ``` error: conversion to non-scalar type requested ``` I tried accessing the elements by declaring a pointer to a structure. I did well in this case, but in this case I do not declare a pointer to a structure and I have to access the elements. How can I overcome this error. Thanks for any help in advance ``` #include<stdio.h> typedef struct { unsigned long a:8; unsigned long b:8; unsigned long c:8; unsigned long d:8; }cc; int main() { cc aa ; unsigned long v = 1458; printf("%d\n",sizeof(aa)); aa=v; // aa= (cc)v; printf("%d %d %d %d\n", aa.a,aa.b,aa.c,aa.d); return 0; } ```