此代码适用于 Microchip 的 PIC32MX 微处理器。他们的编译器本质上是 GCC 3.4。
我倾向于使用 GCC 的__packed__
属性将位域打包到一个联合中,然后将它们检索为unsigned char
(即类型双关语)以通过 SPI 或 I2C 发送。这种行为都是由我的实现定义的,并且运行良好。我更喜欢这个而不是一百行左右的掩蔽和移位:)
我的问题是:__packed__
下面的代码中是否有多余的属性?乍一看,我认为工会高层成员可以免去,但我不太确定。或者我可以省略嵌套结构中的那些吗?
// Remember that bitfields cannot straddle word boundaries!
typedef struct
{
/// Some flag #1
unsigned FlagOne : 1 __attribute__((packed));
/// Some flag #2
unsigned FlagTwo : 1 __attribute__((packed));
/// A chunk of data
unsigned SomeData : 5 __attribute__((packed));
// and so on, maybe up to 32 bits long depending on the destination
} BlobForSomeChip;
/// This kind of type-punning is implementation defined. Read Appendix A (A7, A12) of
/// the MPLAB C Compiler for PIC32 MCUs manual.
typedef union
{
/// Access the members of this union to set flags, etc
BlobForSomeChip blobdata __attribute__((packed));
/// As a byte for sending via SPI, I2C etc
unsigned char bytes[4] __attribute__((packed));
} BlobData;