How to get the value a_size
?
First thing first, bit-field is used to limit memory usage, by limiting sizeof()
of a data type. So, the value of bit-field like unsigned int a_size : 3;
is not printed as 3
, instead you have assigned a_size
bit-width to 3.
If you want to print 3
then you have to assign a_size
to 3 instead of defining it's bit-field as 3.
So, first we have initialize it by using some functions which is written below:
#include <stdio.h>
#include <stdbool.h>
struct header {
unsigned int total_size : 6;
unsigned int a_size : 3;
unsigned int b_size : 2;
unsigned int c_size : 3;
unsigned int d_size : 2;
};
/*
This function inits the `struct header`.
@param h reference of your variable
@returns false if `h` was NULL, otherwise returns true
*/
int init(struct header *h)
{
if(!h)
return false;
h->a_size = 3;
h->b_size = 2;
h->c_size = 3;
h->d_size = 2;
h->total_size = 6;
return true;
}
int main(void) {
struct header h;
init(&h);
printf("\n=========== HEADER ===========\n");
printf("a_size : %d\n", h.a_size);
return 0;
}