Bitfileds on 5282

キャンセル
次の結果を表示 
表示  限定  | 次の代わりに検索 
もしかして: 

Bitfileds on 5282

1,319件の閲覧回数
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 返信

482件の閲覧回数
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 件の賞賛
返信