Search code examples
cenumsbit-fields

enum in bitfield - ANSI C


I didn't find it elsewhere so I wonder if it's possibile to use as bitfield such notation:

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;

I have a problem with bitfield: 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;

When I use value SPI_MODE3 (similiar for SPI_MODE2), Compiler produces a warning:

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

I can't specify that typedefed enum is unsigned so is there some way how to avoid this problem?


Solution

  • Your bitfield can only actually be -2 if it is a signed bitfield. Since SPIMode_t is signed, there is actually an implicit conversion taking place.

    Use 'unsigned int' as the bitfield type instead of SPIMode_t. If you still get a warning (which will be compiler dependent) cast the assignment to an unsigned int.