简体   繁体   English

分配给结构成员的值不正确

[英]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 . 最后的两个成员是与另一个相似的枚举,第一个只是一个unsigned char This struct is used to initialize a register on a microcontroller, so I limited each field to 2 bits. struct用于初始化微控制器上的寄存器,因此我将每个字段限制为2位。

I assign the members of the struct like so: 我这样分配struct的成员:

 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. 但是, eClockSource成员的行为异常。 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? Code Composer调试器将字段显示为32位而不是2,并且最后分配给该字段的值是-2而不是2。经过一些试验,我发现写0导致它读为0,写5为结果显示为2 ...这是怎么回事? The other members behave just fine. 其他成员的行为也很好。 It is a TI ARM compiler for a 32-bit controller. 它是用于32位控制器的TI ARM编译器。

It's non-portable to have a bit-field of a type other than _Bool , signed int , int or unsigned int . 除了_Boolsigned intintunsigned int之外,其他类型的位域都是不可移植的。

A signed bitfield of size :2 can hold values of -2, -1, 0, 1 . 大小为:2的带符号位字段可以容纳-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 . 听起来好像您想要的是无符号位域,所以我建议使用unsigned int

NB. NB。 in a bit-field, it's implementation-defined whether int means signed int or unsigned int . 在位字段中, int是有signed int还是unsigned int ,由实现定义。 So if you use plain int it may still give different ranges depending on compiler or settings. 因此,如果您使用Plain int ,则根据编译器或设置,它可能仍会给出不同的范围。

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. 作为32位。 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. 如果需要特定宽度的位域,最好的方法是使用按位运算符插入和提取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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