首先,我不关心可移植性,并且可以安全地假设字节顺序不会改变.假设我读取了硬件寄存器值,我想将该寄存器值覆盖在位域上,这样我就可以参考寄存器中的各个字段而不使用位掩码.
编辑:修复了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*>(®isterValue));
}
/// 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;
}
Run Code Online (Sandbox Code Playgroud)
Bitfields无法正常工作.您不能将标量值分配给struct完整的位域.看起来你已经知道了,因为你使用过reinterpret_cast,但由于reinterpret_cast不能保证做得非常多,它只是滚动骰子.
如果要在位域结构和标量之间进行转换,则需要对值进行编码和解码.
HW_Register(unsigned char value)
: field1( value & 3 ),
field2( value >> 2 & 3 ),
field3( value >> 4 & 7 )
{}
Run Code Online (Sandbox Code Playgroud)
编辑:您没有得到任何输出的原因是与字段中的数字对应的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;
Run Code Online (Sandbox Code Playgroud)
不要这样做
*this = *(reinterpret_cast<HW_Register*>(®isterValue));
Run Code Online (Sandbox Code Playgroud)
'this'指针不应该以这种方式摆弄:
HW_Register reg(val)
HW_Register *reg = new HW_Register(val)
Run Code Online (Sandbox Code Playgroud)
这里'这'在记忆中有两个不同的地方
相反,有一个内部联合/结构来保存值,这样很容易来回转换(因为你对可移植性不感兴趣)
例如
union
{
struct {
unsigned short field1:2;
unsigned short field2:4;
unsigned short field3:2;
...
} bits;
unsigned short value;
} reg
Run Code Online (Sandbox Code Playgroud)
编辑:足够真实,名称为'register'
| 归档时间: |
|
| 查看次数: |
3467 次 |
| 最近记录: |