簡體   English   中英

如何使用C ++構造函數初始化位域?

[英]How to initialize bitfields with a C++ Constructor?

首先,我不關心可移植性,並且可以安全地假設字節順序不會改變。 假設我讀取了硬件寄存器值,我想將該寄存器值覆蓋在位域上,這樣我就可以參考寄存器中的各個字段而不使用位掩碼。

編輯:修復了GMan指出的問題,並調整了代碼,以便將來讀者更清楚。

請參閱: Anders K.和Michael J的答案,以獲得更有說服力的解決方案。

#include <iostream>

/// \class HardwareRegister
/// Abstracts out bitfields in a hardware register.
/// \warning  This is non-portable code.
class HardwareRegister
{
   public:
      /// Constructor.
      /// \param[in]  registerValue - the value of the entire register. The
      ///                             value will be overlayed onto the bitfields
      ///                             defined in this class.
      HardwareRegister(unsigned long registerValue = 0)
      {
         /// Lots of casting to get registerValue to overlay on top of the
         /// bitfields
         *this = *(reinterpret_cast<HardwareRegister*>(&registerValue));
      }


      /// Bitfields of this register.
      /// The data type of this field should be the same size as the register
      /// unsigned short for 16 bit register
      /// unsigned long for 32 bit register.
      ///
      /// \warning Remember endianess! Order of the following bitfields are
      ///          important.
      ///          Big Endian    - Start with the most signifcant bits first.
      ///          Little Endian - Start with the least signifcant bits first.
      unsigned long field1: 8;
      unsigned long field2:16;
      unsigned long field3: 8;
}; //end class Hardware


int main()
{

   unsigned long registerValue = 0xFFFFFF00;
   HardwareRegister  testRegister(registerValue);

   // Prints out for little endianess machine
   // Field 1 = 0
   // Field 2 = 65535
   // Field 3 = 255
   std::cout << "Field 1 = " << testRegister.field1 << std::endl;
   std::cout << "Field 2 = " << testRegister.field2 << std::endl;
   std::cout << "Field 3 = " << testRegister.field3 << std::endl;
}

Bitfields無法正常工作。 您不能將標量值分配給充滿位域的struct 看起來你已經知道了,因為你使用了reinterpret_cast ,但由於reinterpret_cast不能保證做得非常多,所以它只是擲骰子。

如果要在位域結構和標量之間進行轉換,則需要對值進行編碼和解碼。

    HW_Register(unsigned char value)
      : field1( value & 3 ),
        field2( value >> 2 & 3 ),
        field3( value >> 4 & 7 )
        {}

編輯 :您沒有得到任何輸出的原因是與字段中的數字對應的ASCII字符是非打印的。 嘗試這個:

std::cout << "Field 1 = " << (int) testRegister.field1 << std::endl;
std::cout << "Field 2 = " << (int) testRegister.field2 << std::endl;
std::cout << "Field 3 = " << (int) testRegister.field3 << std::endl;

不要這樣做

 *this = *(reinterpret_cast<HW_Register*>(&registerValue));

'this'指針不應該以這種方式擺弄:

HW_Register reg(val)
HW_Register *reg = new HW_Register(val)

這里'這'在記憶中有兩個不同的地方

相反,有一個內部聯合/結構來保存值,這樣很容易來回轉換(因為你對可移植性不感興趣)

例如

union
{
   struct {
     unsigned short field1:2;
     unsigned short field2:4;
     unsigned short field3:2;
    ...
   } bits;
   unsigned short value;
} reg

編輯:足夠真實,名稱為'register'

嘗試這個:

class HW_Register
{
public:
    HW_Register(unsigned char nRegisterValue=0)
    {
        Init(nRegisterValue);
    }
    ~HW_Register(void){};

    void Init(unsigned char nRegisterValue)
    {
        nVal = nRegisterValue;
    }

    unsigned Field1() { return nField1; }
    unsigned Field2() { return nField2; }
    unsigned Field3() { return nField3; }

private:
    union
    {
        struct 
        {
            unsigned char nField1:2;
            unsigned char nField2:4;
            unsigned char nField3:2;
        };
        unsigned char nVal;
    };
};


int main()
{
    unsigned char registerValue = 0xFF;
    HW_Register  testRegister(registerValue);

    std::cout << "Field 1 = " << testRegister.Field1() << std::endl;
    std::cout << "Field 2 = " << testRegister.Field2() << std::endl;
    std::cout << "Field 3 = " << testRegister.Field3() << std::endl;

    return 0;
}
HW_Register(unsigned char registerValue) : field1(0), field2(0), field3(0) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM