gpt4 book ai didi

C++ 如何从 uchar 数组中填充结构的位字段?

转载 作者:太空宇宙 更新时间:2023-11-04 08:08:10 26 4
gpt4 key购买 nike

我有一个无符号字符数组,其值如下:

u_char *t_header[4]; //filled with values 0x00000047,0x00000004,0x00000093,0x00000012

我有一个结构如下:

            #pragma pack(push, 1)
typedef struct th_struct {
unsigned s_byte : 8;
unsigned t_e_indicator : 1;
unsigned p_u_s_indicator : 1;
unsigned t_priority : 1;
unsigned id : 13;
unsigned t_s_control : 2;
unsigned a_f_control : 2;
unsigned c_counter : 4;
}th_struct;
#pragma pack(pop)

我正在尝试按以下方式填充结构字段:

            const struct  th_struct *tsh;
tsh = (struct th_struct*)(t_header);

它按预期用十六进制的 71 = 0x47 填充 tsh->s_byte 但其余字段都是 0

我必须做些什么才能用 u_char *t_header[4] 值正确填充 struct th_struct *tsh,如下所示?


0100 0111 .... .... .... .... .... = (0x00000047) tsh->s_byte
.... .... 0... .... .... .... .... = 0 tsh->t_e_indicator
.... .. .0 .. .... .... .... .... .... = 0 tsh->p_u_s_indicator
.... .. ..0。 .... .... .... .... .... = 0 tsh->t_priority
.... .... ...0 0100 1001 0011 .... .... = (0x00000493) tsh->id
.... .... .... .... .... 00 .. .... = (0x00000000) tsh->t_s_control
.... .... .... .... .... ..01 .... = (0x00000001) tsh->a_f_control
.... .... .... .... .... .... 0010 = 2 tsh->c_counter

谢谢!

最佳答案

首先你这里有个问题:

u_char *t_header[4];

那是 4 个指针 - 而不是 4 个 u_char。你可能想要:

u_char t_header[4];

下一个问题是位字段的布局是依赖于实现的。

因此,编写假定特定布局的代码(通常)不是一个好主意。这样的代码只能在编写代码时使用的特定系统上运行,即代码是不可移植的。

我建议您使用移位运算符 >>> 和按位与运算符 & 来准确选择所需的位:

unsigned char t_header[4] = {0x47, 0x04, 0x93, 0x12};
th_struct tsh;

tsh.s_byte = t_header[0];
tsh.t_e_indicator = (t_header[1] >> 7) & 0x1;
tsh.p_u_s_indicator = (t_header[1] >> 6) & 0x1;
tsh.t_priority = (t_header[1] >> 5) & 0x1;
tsh.id = ((unsigned)(t_header[1] & 0x1f) << 8) + t_header[2];
tsh.t_s_control = (t_header[3] >> 6) & 0x3;
tsh.a_f_control = (t_header[3] >> 4) & 0x3;
tsh.c_counter = t_header[3] & 0xf;

printf("s_byte=%x\n", tsh.s_byte);
printf("t_e_indicator=%x\n", tsh.t_e_indicator);
printf("p_u_s_indicator=%x\n", tsh.p_u_s_indicator);
printf("t_priority=%x\n", tsh.t_priority);
printf("id=%x\n", tsh.id);
printf("t_s_control=%x\n", tsh.t_s_control);
printf("a_f_control=%x\n", tsh.a_f_control);
printf("c_counter=%x\n", tsh.c_counter);

那么你也可以避免使用压缩结构。

关于C++ 如何从 uchar 数组中填充结构的位字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41221009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com