c-如何获取结构中的位大小



我想在标题结构中打印a_size,如"a_size=3";但是,它打印";a_size=1";。

如何获取值a_size

#include <stdio.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;
};
int main() {
struct header h;
printf("n=========== HEADER ===========n");
printf("a_size : %dn", h.a_size);
return 0;
}

如何获取值a_size

首先,位字段用于通过限制数据类型的sizeof()来限制内存使用。因此,像unsigned int a_size : 3;这样的位字段的值不会打印为3,而是将a_size位宽分配给3。

如果要打印3,则必须将a_size分配给3,而不是将其位字段定义为3。

因此,首先我们必须使用下面写的一些函数来初始化它:

#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 : %dn", h.a_size);
return 0;
}

最新更新