Write equivalent of x == y using bit

What is a C expression equivalent to x == y that only uses bit-level (|,~,^,&) and logical (&&,||,!) operations? It should return 1 when x and y are equal, 0 otherwise.


The expression x==y is equivalent to the logical biconditional expression x<->y (Evaluates to true iff x and y are equivalent). The biconditional is the inverse of the exclusive or (Evaluates to true if x and y are not equivalent), so

x==y is equivalent to

NOT ( x XOR y)

which is

bit: ~(x^y)

logical doesn't have XOR , so given that x ⊕ y = (x ∨ y) ∧ !(x ∧ y)

logical: !((x || y) && !(x && y))

NOTE: The above expressions are logically (a better word might be algebraicly?) equivalent. The bitwise comparison will of course just look at each bit. As @chux pointed out, this may give an unexpected result if 2 numbers are arithmetically equivalent, but have a different bit pattern. And the same issue arises in C++ if you are comparing objects that have overridden the == operator. A gotcha for the logical version is that type coercion may occur if x and y are not the same variable type.

链接地址: http://www.djcxy.com/p/57572.html

上一篇: 用位运算符饱和签名整数乘法

下一篇: 使用位写入x == y的等价物