C宏设置多个位 [英] C macro to set multiple bits

查看:44
本文介绍了C宏设置多个位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在C语言中的微控制器上工作.这部分涉及更改寄存器中的位值.我提出了一些宏来简化操作:

I am working on a microcontroller in C. Part of this involves changes bit values in registers. I have come up with a few macros to make things easier:

#define BIT_SET(addr, shift) (addr | (1 << shift))
#define BIT_RESET(addr, shift) (addr & ~(1 << shift))
#define BIT_GET(addr, shift) (addr & (1 << shift))
...
reg1 = BIT_SET(reg1, 3); //set bit 3
...

但是,现在我要创建一个宏,该宏将一次更改几个位.例如,可能想要将 10101010 的前3位更改为 110 ,从而产生数字 11001010 .

However, now I want to make a macro which will change several bits at a time. For example, may want to change the first 3 bits of 10101010 to 110, resulting in the number 11001010.

我可以在C语言中执行此操作吗?还是我走错路了?

Can I do this in C? Or am I approaching this the wrong way?

推荐答案

您可以引入一个全角掩码,该掩码定义要设置的位.例如.要设置前3位,请使用0xe0(二进制11100000).

You could introduce a fullwidth mask which defines the bits you want to set. E.g. for setting the first 3 bits use 0xe0, which is in binary 11100000.

连同该掩码一起,提供还要以全角写入的值.
例如.前三个位中所需的二进制110为0xc0.

Along with that mask, provide the value to write also in full width.
E.g. 0xc0 for the desired binary 110 in the first three bits.

然后,只需要写一点所需的位就需要一点点操作魔术.

Then a little bit-operatino magic is needed to only write the desired bit positions.

#define MULTIBIT_SET(addr, mask, value) (((addr)&((0xff)^(mask)))|((value)&(mask)))

此处(((0xff)^(mask))会反转掩码,因此与此进行与"运算会从值中删除现有位.
(((value)&(mask))是该值,但仅在所需位置设置了位,即,这防止了在其他位置进行不需要的位设置.

Here ((0xff)^(mask)) inverts the mask, so that anding with this deletes the existing bits from the value.
((value)&(mask)) is the value but with only set bits in the desired positions, i.e. this prevents undesired setting of bits elsewhere.

总之,将这两个部分相加,即可获得所需的结果.

In total, oring the two parts, gives you the desired result.

这里有一个设计选择,我要提到:
称之为偏执狂.如果有人告诉我我只想将前三位设置为该值,该值在其他位置有位",那么我宁愿以这种方式确保安全,即删除其他位".
是的,我假设无意设置位比没有设置位的风险更大,这是一个问题.

There is a design choice here, which I want to mention:
Call it paranoia. If somebody tells me "I want to set only the first three bits, to this value which has bits elsewhere", then I prefer to take it safe this way, i.e. removing the "elsewhere bits".
Yes, I am assuming that setting bits without intention is more of a risk than not setting them, which is a matter of taste.

这篇关于C宏设置多个位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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