【问题标题】:enum in bitfield - ANSI C位域中的枚举 - ANSI C
【发布时间】:2014-08-20 09:25:05
【问题描述】:

我没有在其他地方找到它,所以我想知道它是否可以用作位域这样的符号:

typedef struct
{
    union
    {
        u8 SPI_Cfg;            //!< Bit mode and bit order merged, as in the SPI CONFIG register 
        struct
        {
            SPIBitOrder_t BitOrder : 1;   //!< SPI master bit order 
            SPIMode_t Mode : 2;             //!< SPI master mode 
            u8 : 5;                                 //!< Padding 
        }Fields;
    }Config;    
    SPIFrequency_t Frequency;  //!< SPI master frequency 
    u8 Pin_SCK;                //!< SPI master SCK pin 
    u8 Pin_MOSI;               //!< SPI master MOSI pin 
    u8 Pin_MISO;               //!< SPI master MISO pin 
    u8 Pin_CSN;                //!< SPI master chip select pin 
} SPIConfig_t;

我的位域有问题:SPIMode_t Mode : 2;

//!  SPI mode
typedef enum
{
    //------------------------Clock polarity 0, Clock starts with level 0-------------------------------------------
    SPI_MODE0 = 0,          //!< Sample data at rising edge of clock and shift serial data at falling edge 
    SPI_MODE1,              //!< sample data at falling edge of clock and shift serial data at rising edge 
    //------------------------Clock polarity 1, Clock starts with level 1-------------------------------------------
    SPI_MODE2,              //!< sample data at falling edge of clock and shift serial data at rising edge 
    SPI_MODE3               //!< Sample data at rising edge of clock and shift serial data at falling edge 
} SPIMode_t;

当我使用值 SPI_MODE3(与 SPI_MODE2 类似)时,编译器会产生警告:

implicit truncation from 'int' to bitfield changes value from 2 to -2

我无法指定 typedefed enumunsigned 那么有什么方法可以避免这个问题吗?

【问题讨论】:

    标签: c enums bit-fields


    【解决方案1】:

    如果它是一个有符号的位域,你的位域实际上只能是 -2。由于 SPIMode_t 已签名,因此实际上发生了隐式转换。

    使用 'unsigned int' 作为位域类型,而不是 SPIMode_t。如果您仍然收到警告(这将取决于编译器)将赋值转换为无符号整数。

    【讨论】:

    • 谢谢,这就是我必须做的,使用 unsigned char 代替。但是对于稍后将使用我的代码的人来说,使用 typdefed 枚举会更清楚,这是我的意图。
    • 你可以保持你的位域签名并使其宽度为 3 位。
    猜你喜欢
    • 2018-09-20
    • 2011-04-26
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    相关资源
    最近更新 更多