位域中的枚举 - ANSI C

时间:2014-08-20 09:25:05

标签: c enums bit-fields

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

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;

我遇到了bitfield问题: SPIMode_t模式: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所以有什么方法可以避免这个问题吗?

1 个答案:

答案 0 :(得分:2)

如果是有符号的位域,那么你的位域实际上只能是-2。由于SPIMode_t已签名,因此实际上存在隐式转换。

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