programing tip

조건부 XOR?

itbloger 2020. 10. 20. 07:24
반응형

조건부 XOR?


C #에 조건부 XOR연산자 가없는 이유는 무엇입니까?

예:

true  xor false = true
true  xor true  = false
false xor false = false

C #에서 조건부 연산자는 필요한 경우 에만 보조 피연산자를 실행 합니다 .

XOR 정의에 따라 두 값을 모두 테스트 해야 하므로 조건부 버전은 어리석은 것입니다.

:

  • 논리적 AND : &-매번 양쪽을 테스트합니다.

  • 논리적 OR : |-매번 양쪽을 테스트합니다.

  • 조건부 AND : &&-첫 번째면이 참인 경우 두 번째 면만 테스트합니다.

  • 조건부 OR : ||-첫 번째면이 거짓이면 두 번째 면만 테스트합니다.


질문이 조금 구식이지만 ...

이 연산자가 작동하는 방식은 다음과 같습니다.

true xor false = true
true xor true = false
false xor false = false

이것은! = 연산자가 bool 유형에서 작동하는 방식입니다.

(true != false) // true
(true != true) // false
(false != false) // false

보시다시피 ^^존재하지 않는 것은 기존의!=


논리 XOR 연산자가 있습니다. ^

문서 : C # 연산자^ 연산자


설명처럼 ^ 연산자는 정수 유형과 부울 모두에서 작동합니다.

참조 MSDN의 ^ 연산자 (C # 참조) :

이진 ^ 연산자는 정수 유형 및 부울에 대해 사전 정의됩니다. 정수 유형의 경우 ^는 피연산자의 비트 배타적 OR을 계산합니다. bool 피연산자의 경우 ^는 피연산자의 논리 배타적 또는 논리 연산을 계산합니다. 즉, 피연산자 중 정확히 하나가 참인 경우에만 결과가 참입니다.

이 질문이 제기 된 2011 년 이후로 문서가 변경되었을 수 있습니다.


Mark L의 질문에 따라 올바른 버전은 다음과 같습니다.

 Func<bool, bool, bool> XOR = (X,Y) => ((!X) && Y) || (X && (!Y));

다음은 진리표입니다.

 X | Y | Result
 ==============
 0 | 0 | 0
 1 | 0 | 1
 0 | 1 | 1
 1 | 1 | 0

참조 : 독점 OR


네, 그렇습니다.

bool b1 = true;
bool b2 = false;
bool XOR = b1 ^ b2;

조건부 xor는 존재하지 않지만 xor가 부울에 대해 정의되고 모든 조건부 비교가 부울로 평가되므로 논리 xor를 사용할 수 있습니다.

따라서 다음과 같이 말할 수 있습니다.

if ( (a == b) ^ (c == d))
{

}

논리 xor 연산자 는 있지만 조건부 xor 연산자 ^는 없습니다 . 다음을 사용하여 두 값 A와 B의 조건부 xor를 얻을 수 있습니다.

A ? (!B) : B

괄호는 필요하지 않지만 명확성을 위해 추가했습니다.

The Evil Greebo가 지적했듯이 이것은 두 표현을 모두 평가하지만 xor는 and and or 처럼 단락 될 수 없습니다 .


당신이 사용할 수있는:

a = b ^ c;

C / C ++ 에서처럼


There is no such thing as conditional (short-circuiting) XOR. Conditional operators are only meaningful when there's a way to definitively tell the final outcome from looking at only the first argument. XOR (and addition) always require two arguments, so there's no way to short-circuit after the first argument.

If you know A=true, then (A XOR B) = !B.

If you know A=false, then (A XOR B) = B.

In both cases, if you know A but not B, then you don't know enough to know (A XOR B). You must always learn the values of both A and B in order to calculate the answer. There is literally no use case where you can ever resolve the XOR without both values.

Keep in mind, XOR by definition has four cases:

false xor true  = true
true  xor false = true
true  xor true  = false
false xor false = false

Again, hopefully it's obvious from the above that knowing the first value is never enough to get the answer without also knowing the second value. However, in your question, you omitted the first case. If you instead wanted

false op true  = false (or DontCare)
true  op false = true
true  op true  = false
false op false = false

then you can indeed get that by a short-circuiting conditional operation:

A && !B

But that's not an XOR.


This question has been affectively answered, but I came across a different situation. It's true that there is no need for a conditional XOR. It's also true that the ^ operator can be used. However, if you need to only test the "true || false" status of the operands then ^ can lead to trouble. For example:

void Turn(int left, int right)
{
    if (left ^ right)
    {
        //success... turn the car left or right...
    }
    else
    {
        //error... no turn or both left AND right are set...
    }
}

In this example, if left is set to 10 (0xa) and right is set to 5 (0x5) the "success" branch is entered. For this (simplistic if silly) example, this would result in a bug since you shouldn't turn left AND right at the same time. What I gathered from the questioner is not that he actually wanted a conditional, but a simple way to perform the true/false on the values as passed to the xor.

A macro could do the trick:

#define my_xor(a, b) ( ((a)?1:0) ^ ((b)?1:0) )

Feel free to slap me around if I'm off the mark :o)

I read jimreed's answer below after I posted this (bad Yapdog!) and his is actually simpler. It would work and I have absolutely no idea why his answer was voted down...

참고URL : https://stackoverflow.com/questions/6507850/conditional-xor

반응형