Bitfield Enumeration - ANSI C
I haven't found it elsewhere, so I'm wondering if it is possible to use the following notation as a bitfield:
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 bitfield problem: 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 the SPI_MODE3 value (similar to SPI_MODE2), the compiler issues a warning:
implicit truncation from 'int' to bitfield changes value from 2 to -2
I cannot tell what typedefed enum
is unsigned
, so is there a way to avoid this problem?
+3
source to share
1 answer
Your bitfield can actually only be -2 if it's a bit-bit. Since the SPIMode_t is signed, an implicit conversion actually occurs.
Use "unsigned int" as the bitfield type instead of SPIMode_t. If you still get a warning (which will be compiler dependent) then pass the assignment to an unsigned int.
+2
source to share