0

この形式の typedef を使用して、マイクロプロセッサ レジスタとその中のビット フィールドへのアクセスを簡素化します。

  typedef union
  {
     uint8_t        u8Byte;           ///< REG_8 as unsigned byte
     int8_t         i8Byte;           ///< REG_8 as signed byte
     struct
     {
        unsigned b0:1;                ///< Bit 0 of REG_8 type
        unsigned b1:1;                ///< Bit 1 of REG_8 type
        unsigned b2:1;                ///< Bit 2 of REG_8 type
        unsigned b3:1;                ///< Bit 3 of REG_8 type
        unsigned b4:1;                ///< Bit 4 of REG_8 type
        unsigned b5:1;                ///< Bit 5 of REG_8 type
        unsigned b6:1;                ///< Bit 6 of REG_8 type
        unsigned b7:1;                ///< Bit 7 of REG_8 type
     };
  } REG_8;

残念ながら、sizeof(REG_8)予想される 1 ではなく 2 を返します。REG_16 と REG_32 の同様の定義は、予想どおり 2 と 4 のサイズを返します。sizeof(uint8_t)期待どおり、1をsizeof(int8_t)返します。

タイプは期待どおりに機能します。例えば、

REG_8  a;
a.u8Byte = 4;

は値 1を与えるa.b2ため、アラインメントの問題はありません。

を削除するstructsizeof値が 1 になるため、パディングの問題があるように見えますが、もしそうなら、なぜですか?

誰でもこれを説明できますか?16 ビット プロセッサを対象とする Microchip XC16 コンパイラ (GCC ベース) を使用しています。

4

2 に答える 2

2

お使いのマシンではおそらく sizeof(unsigned)=2 であるため、「符号なし」ビット フィールドは少なくとも 2 バイトを占有します。unsigned を uint8_t に置き換えると、sizeof(REG_8) が 1 になります。

この質問も参照してください: ビットフィールドを持つ構造体のサイズはどのように決定/測定されますか?

于 2015-10-07T21:27:36.257 に答える
0

@twin の考えは正しかったようですが、別の解決策も見つけました。期待値を与える 2 つの選択肢は次のsizeof(REG_8) == 1とおりです。

  typedef union
  {
     uint8_t        u8Byte;           ///< REG_8 as unsigned byte
     int8_t         i8Byte;           ///< REG_8 as signed byte
     struct
     {
        unsigned b0:1;                ///< Bit 0 of REG_8 type
        unsigned b1:1;                ///< Bit 1 of REG_8 type
        unsigned b2:1;                ///< Bit 2 of REG_8 type
        unsigned b3:1;                ///< Bit 3 of REG_8 type
        unsigned b4:1;                ///< Bit 4 of REG_8 type
        unsigned b5:1;                ///< Bit 5 of REG_8 type
        unsigned b6:1;                ///< Bit 6 of REG_8 type
        unsigned b7:1;                ///< Bit 7 of REG_8 type
     } __attribute__((packed));
  } REG_8;

...また...

  typedef union
  {
     uint8_t        u8Byte;           ///< REG_8 as unsigned byte
     int8_t         i8Byte;           ///< REG_8 as signed byte
     struct
     {
        uint8_t b0:1;                ///< Bit 0 of REG_8 type
        uint8_t b1:1;                ///< Bit 1 of REG_8 type
        uint8_t b2:1;                ///< Bit 2 of REG_8 type
        uint8_t b3:1;                ///< Bit 3 of REG_8 type
        uint8_t b4:1;                ///< Bit 4 of REG_8 type
        uint8_t b5:1;                ///< Bit 5 of REG_8 type
        uint8_t b6:1;                ///< Bit 6 of REG_8 type
        uint8_t b7:1;                ///< Bit 7 of REG_8 type
     };
  } REG_8;
于 2015-10-07T21:41:02.090 に答える