gpt4 book ai didi

c++ - 如何使用 C++ 构造函数初始化位域?

转载 作者:太空狗 更新时间:2023-10-29 19:44:53 25 4
gpt4 key购买 nike

首先,我不关心可移植性,可以放心地假设字节顺序不会改变。假设我读取了一个硬件寄存器值,我想将该寄存器值覆盖在位域上,这样我就可以在不使用位掩码的情况下引用寄存器中的各个字段。

编辑:修复了 GMan 指出的问题,并调整了代码,以便 future 的读者更清楚。

请参见: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;
}

最佳答案

不要这样做

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

“this”指针不应该以这种方式摆弄:

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

这里 'this' 在内存中的两个不同位置

取而代之的是有一个内部 union/结构来保存值,这样很容易转换来回(因为你对便携性不感兴趣)

例如

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

编辑:名称“register”足够真实

关于c++ - 如何使用 C++ 构造函数初始化位域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3562964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com