从H / W寄存器读取位字段 [英] Bit fields for reading from H/W registers

查看:166
本文介绍了从H / W寄存器读取位字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读第2,第5和第6位从32位寄存器。我已经决定使用结构位字段来存储它们。在下面的数据结构是否正确?

I want to read the 2nd, 5th and the 6th bit from a 32-bit register. I have decided to use struct bit fields to store them. Is the following data structure correct?

struct readData
{
  int unwanted:1;
  int reqbit1:1;
  int unwanted1:2;
  int reqbit2:2;
  int unwanted2:26;
};

我不知道如何创建位域。我将使用将从H / W寄存器直接复制字节这种结构的API。在这种情况下,将reqbit1包含第2比特?按我的理解,编译器下发的第一位为int变量,第二位获分配到另一个int变量等等reqbit1不会从寄存器中读取任何数据。是不是下面的工会更适合这种情况呢?

I'm not sure about how the bit fields are created. I'm going to use an API that will copy bytes from the h/w register to this structure directly. In that case, will reqbit1 contain the 2nd bit? As per my understanding, the compiler allots the first bit to an int variable and the 2nd bit is alloted to another int variable and so the reqbit1 won't have any data read from the register. Isn't the following union more suitable for this situation?

union readData
{
  struct readBits{
  bool unwanted:1;
  bool reqbit1:1;
  xxx unwanted1:2;
  short reqbit2:2;
  xxx unwanted2:26;
  };
  int regValue;
};

如果这是正确的,我应该怎么申报unwanted2作为?

If this is right, what should I declare unwanted2 as?

推荐答案

从C标准:一个单位(高阶到低阶或低阶到高阶内的位域的分配顺序)是实现定义。

From the C standard: "The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined."

所以,你不应该使用位域所在的顺序问题。

So you shouldn't use bitfields where the order matters.

使用明确的遮蔽,而是转向:

Use explicit masking and shifting instead:

reqbit1 = (w >> 1) & 1;    
reqbit2 = (w >> 4) & 3;

reqbit1 = (w & 0x00000002) >> 1;    
reqbit2 = (w & 0x00000010) >> 4;

和对其他方向

w = (reqbit1 << 1) | (reqbit2 << 4);

在不必要的零件通常名为保留1 等。

这篇关于从H / W寄存器读取位字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆