About BitField

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

About BitField

661 Views
zy
Contributor I

Hello! I'm using XET256  CodeWarrior IDE version V5.9.0

 

I have defined a UNION  

typedef union{     struct{        word XLength:8;        word nouse:5;        word datatype:1;        word operation:2;            }Sx;  struct{  word XLength:5;  word YLength:8;  word datatype:1;  word operation:2; }Sxy;    struct{  word lbits: 10;  word invalidFlag: 1;  word hbits: 5; }Sinvalid;  word w;}UIndexType;UIndexType typeP;typeP.w=0x401e;

 but in debug ,the result is  so wrong ,

typeP    Sx                          <2> struct        XLength                 0x40 unsigned char [0:8]        nouse                   0x1e unsigned char [0:5]        datatype                0x0  unsigned char [5:1]        operation               0x0  unsigned char [6:2]    Sxy                         <2> struct        XLength                 0x1e unsigned short[0:5]        YLength                 0x0  unsigned shor[5:8]        datatype                0x0  unsigned short[13:1]        operation               0x1  unsigned short[14:2]    Sinvalid                    <2> struct        lbits                   0x1e unsigned short[0:10]        invalidFlag             0x0  unsigned shor[10:1]        hbits                   0x8  unsigned short[11:5]    w                      0x401e unsigned int  

And if I define  word  XLength :9   word nouse:5  the result is right , 

what's wrong of that ? The same code in CodeWarrior IDE version v4.6 is al right.I am being crazy. if there are some bugs in IDE Please tell me  I'm in hurry.

Labels (1)
0 Kudos
Reply
2 Replies

510 Views
kef
Specialist I

I see no problem with this. In C you can't expect particular order, alignment, or padding of struct or union elements. Bitfields are there to allow saving memory. Having big arrays of small data types it may make sense to use bitfields to save space.

Union is there in C to reuse the same memory to store different types. For example you may have struct, which has two fields, one enum describes data type like char, int, float etc, another field is a union of char/int/float etc.

What you do is some kind of cheating or tricky programming. It is bad practice, at least because your code is not portable and won't work with all compilers and all targets.

You may look in compiler settings. I think there is an option to specify order of bitfields members, which is of no interest to people doing portable programs. Portable would be to use << >> | & operators to extract and put fields into integers or arrays of chars.

0 Kudos
Reply

510 Views
zy
Contributor I

Thankyou ! I will change code to avoid this problem .

0 Kudos
Reply