我正在尝试检查 int x
的任何一位是否等于 1,答案是 !!x
。我用谷歌搜索了一下,但没有找到任何关于为什么这是正确的信息。
假设我有一个数字 x
是 1010
。
!x
会是什么? !x
和 ~x
有什么区别?
最佳答案
!
是一个逻辑运算符,它取标量类型操作数的值。
引用 C11
,章节 §6.5.3.3,一元算术运算符
The result of the logical negation operator
!
is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has typeint
. [...]
OTOH,~
是一个按位运算符,它对整数类型的操作数执行按位求反。
相关,
The result of the
~
operator is the bitwise complement of its (promoted) operand (that is, each bit in the result is set if and only if the corresponding bit in the converted operand is not set). The integer promotions are performed on the operand, and the result has the promoted type. [...]
例如,考虑二进制数 10
。
!10
是0
。~10
是01
。
编辑:
FWIW,如果你使用 !!
,你得到的结果不是 0 就是 1。OTOH,如果你使用 ~~
,你会得到原始值操作数。
关于c - C 中的 ~~x 和 !!x 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35205186/