c - C 中的 ~~x 和 !!x 有什么区别?

标签 c bitwise-operators logical-operators negation

我正在尝试检查 int x 的任何一位是否等于 1,答案是 !!x。我用谷歌搜索了一下,但没有找到任何关于为什么这是正确的信息。

假设我有一个数字 x1010!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 type int. [...]

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

  • !100
  • ~1001

编辑:

FWIW,如果你使用 !!,你得到的结果不是 0 就是 1。OTOH,如果你使用 ~~,你会得到原始值操作数。

关于c - C 中的 ~~x 和 !!x 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35205186/

相关文章:

python - 不使用 numpy.logic_or 的逻辑或

c# - 运算符 '||' 不能应用于类型 'bool?' 和 'bool?' 的操作数

c++ - 使用二进制空间划分树的多边形测试中的快速点

c - 预期的主要错误总是出现在 c 中

java - 位运算符在 Java 中究竟是如何工作的?

Python boolean 和逻辑运算符

python - 将大块文本转换为图像的算法? (由图像边缘定义)

c - 匹配 ls 命令输出

c - 这段C代码执行后j的值是多少?

c++ - 完美实现按位非(~)运算符(翻转位)