Bitfileds on 5282

取消
显示结果 
显示  仅  | 搜索替代 
您的意思是: 

Bitfileds on 5282

1,320 次查看
SVC2
Contributor II
Hi,
 
Having hard time with bit fields. In the following snippets,
 
Code:
//-----------------------------------------------typedef unsigned short int      uint16//-----------------------------------------------typedef struct { unsigned int source : 5;  unsigned int msg_id:  3;  unsigned int msg_type: 1;  unsigned int request_type: 1;  unsigned int data_type: 6; } BitFields_T;//-----------------------------------------------typedef union { BitFields_T b; uint16 word16;} HEADER_T;//-----------------------------------------------int main(void){  HEADER_T Var; Var.word16=0;  Var.b.source=1;}

 
I was expecting to have Var.word16==1. Instead I have Var.word16==2048 (shifted by 12 ).
 
Any hints?
 
Thanks,
S.

 
标签 (1)
0 项奖励
回复
1 回复

483 次查看
CrasyCat
Specialist III
Hello
 
The problem with bitfields in ANSI C is that they are not portable across compiler vendor or architecture.
The ANSI C standard does not specify i how a bitfield might be allocated in memory.
 
Depending on the vendor and architecture it might be LSB first or MSB first.
There might also be some padding bits between the fields.
 
CodeWarrior for Coldfire uses MSB first as allocation scheme.
 
With the syntax you are using, the compiler will allocate the bits as follows:
  Source : bit 15-10
  msg_id: Bit 0-8
  msg_type: Bit 7
  request_type: bit 6
  dataType: bit 0-5
 
If you wish to get Source allocated on bit 0-4 you need to define your bitfield as follows:
typedef struct {
 unsigned int data_type: 6; 
 unsigned int request_type: 1; 
 unsigned int msg_type: 1; 
 unsigned int msg_id:  3; 
 unsigned int source : 5;
} BitFields_T;
CrasyCat
0 项奖励
回复