【发布时间】:2017-05-04 09:52:34
【问题描述】:
我有一个 unsigned char 数组,其值如下:
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
谢谢!
【问题讨论】:
-
首先这真的取决于你平台的字节序...
-
1) 您没有 uchar 数组 2) 您不能通过将某些内容分配给指向结构的指针来填充结构。请展示一个完整的代码示例。
-
sizeof(th_struct) = 4和sizeof(t_header) = 32 -
第二个
u_char *t_header[4];可能是 32 字节,不适合 32 位 结构.... -
感谢您的回答。我看到
sizeof(th_struct) = 4 and sizeof(t_header) = 32不一样。我想我必须将 t_header 数组转换为 4 个字节的东西,例如0x47049312但如何?
标签: c++ c arrays struct binary