关于C中test_bit宏的问题
我在 C 中使用了以下宏:
#define test_bit(_n,_p) !! ( _n & ( 1u << _p))
我已经研究了该宏,但我需要确定宏中双重否定的使用,以及它与宏定义的行为有何不同:
#define test_bit(_n,_p) ( _n & ( 1u << _p))
I've used the following macro in C:
#define test_bit(_n,_p) !! ( _n & ( 1u << _p))
I've studied the macro but I need to determine the use of the double negative in the macro, and how it behaves differently from the macro definition :
#define test_bit(_n,_p) ( _n & ( 1u << _p))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
想想当您测试特定位时会发生什么:
如果您像这样保留它,您的结果将是位掩码本身。
现在考虑其双重(逻辑,而不是按位)否定,这与不执行任何操作不同:
换句话说,
!!4
为您提供1
而不是4
,这保证您将获得0/1
真值,而不是0/whatever-the-bitmask-was< /代码> 值。
以下程序显示了这一点:
输出:
并按预期
Think about what happens when you test a specific bit:
If you left it like that, your result would be the bitmask itself.
Now consider the double (logical, not bitwise) negation of that, which is not the same as doing nothing:
In other words,
!!4
gives you1
rather than4
and this guarantees that you will get a0/1
truth value rather than a0/whatever-the-bitmask-was
value.The following program shows this in action:
and it outputs:
as expected.
如果将宏与一些算术或位运算符链接起来,它的行为会有所不同。例如,如果您有
,并且
结果将与您的结果不同
,并且双重否定只是 另一种编写
!= 0 的方式
。It will behave differently if you chain the macro with some arithmetic or bitwise operators. For example if you have
and
the result will differ to the one which you have with
And double negation is just another way of writing
!= 0
.基本上,双重否定的目的是将宏返回的值限制为 0 和 1。在
(1) 中,这两个定义等效。在 (2) 中,第一个定义始终设置
array[0]
或array[1]
,而第二个定义则不然。Basically, the purpose of double negation is to constrain values returned by the macro to 0 and 1. In
In (1), both of the definitions work equivalently. In (2), the first definition always sets
array[0]
orarray[1]
, whereas the second doesn't.