简体   繁体   中英

Value assigned to struct member is incorrect

I am completely clueless as to what is going on here and would really like to know.

I have an enum:

typedef enum
{
    TAxCLK = 0,
    ACLK,
    SMCLK,
    INCLK

} TIMER_A_CLOCK_E;

and a struct:

typedef struct
{
    BYTE byTimerSelection           :2;
    TIMER_A_CLOCK_E eClockSource    :2;
    INPUT_DIV_E eInputDivider       :2;
    TIMER_MODE_E eTimerMode         :2;

} TIMER_A_S;

where the other last two members are enums similar to the other and the first is simply an unsigned char . This struct is used to initialize a register on a microcontroller, so I limited each field to 2 bits.

I assign the members of the struct like so:

 TIMER_A_S stTimerInfo;

 // Setup Timer A
 stTimerInfo.byTimerSelection = 0;
 stTimerInfo.eClockSource = SMCLK;
 stTimerInfo.eInputDivider = INPUT_DIV_1;
 stTimerInfo.eTimerMode = UP;

The eClockSource member, however, is behaving strangely. The Code Composer debugger is showing the field as 32 bits instead of 2 and the value that is assigned to it in the end is -2 instead of 2. After some experimentation, I found that writing 0 results in it reading 0 and writing 5 to it results in it reading 2... What's going on? The other members behave just fine. It is a TI ARM compiler for a 32-bit controller.

It's non-portable to have a bit-field of a type other than _Bool , signed int , int or unsigned int .

A signed bitfield of size :2 can hold values of -2, -1, 0, 1 . Since you seem to be getting those values, it means your implementation is making those bit-fields be signed.

It sounds like you wanted unsigned bitfields instead, so I would suggest using unsigned int .

NB. in a bit-field, it's implementation-defined whether int means signed int or unsigned int . So if you use plain int it may still give different ranges depending on compiler or settings.

The standard allows the compiler to expand a bit field. Many do it for better performance. It is VERY common for compilers to implement

     unsigned somefield: 2 ;

as 32 bits. I discourage using bitfields entirely. They are not portable. If you need bitfields of a specific width, the best way is to insert and extract using bitwise operators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM