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

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);

它用十六进制的tsh->s_byte=71填充0x47,但其余字段都是0
我需要做什么才能正确地用struct th_struct *tsh值填充u_char *t_header[4],如下所示?
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++ - C++如何从uchar数组填充结构的位字段?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41221009/

10-09 02:14