^ 연산자(C# 참조)

업데이트: 2010년 12월

이항 ^ 연산자는 정수 계열 형식과 bool에 대해 미리 정의되어 있습니다. 정수 계열 형식의 경우 ^ 연산자는 피연산자의 비트 배타적 OR를 계산합니다. bool 피연산자의 경우 ^ 연산자는 피연산자의 논리 배타적 논리 OR을 계산합니다. 즉, 두 피연산자 중 하나가 true인 경우에만 결과가 true입니다.

설명

사용자 정의 형식으로 ^ 연산자를 오버로드할 수 있습니다(operator 참조). 정수 계열 형식에 대한 연산은 일반적으로 열거형에서 허용됩니다.

예제

    class XOR
    {
        static void Main()
        {
            // Logical exclusive-OR

            // When one operand is true and the other is false, exclusive-OR 
            // returns True.
            Console.WriteLine(true ^ false);
            // When both operands are false, exclusive-OR returns False.
            Console.WriteLine(false ^ false);
            // When both operands are true, exclusive-OR returns False.
            Console.WriteLine(true ^ true);


            // Bitwise exclusive-OR

            // Bitwise exclusive-OR of 0 and 1 returns 1.
            Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x0 ^ 0x1, 2));
            // Bitwise exclusive-OR of 0 and 0 returns 0.
            Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x0 ^ 0x0, 2));
            // Bitwise exclusive-OR of 1 and 1 returns 0.
            Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x1 ^ 0x1, 2));

            // With more than one digit, perform the exclusive-OR column by column.
            //    10
            //    11
            //    --
            //    01
            // Bitwise exclusive-OR of 10 (2) and 11 (3) returns 01 (1).
            Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x2 ^ 0x3, 2));

            // Bitwise exclusive-OR of 101 (5) and 011 (3) returns 110 (6).
            Console.WriteLine("Bitwise result: {0}", Convert.ToString(0x5 ^ 0x3, 2));

            // Bitwise exclusive-OR of 1111 (decimal 15, hexadecimal F) and 0101 (5)
            // returns 1010 (decimal 10, hexadecimal A).
            Console.WriteLine("Bitwise result: {0}", Convert.ToString(0xf ^ 0x5, 2));

            // Finally, bitwise exclusive-OR of 11111000 (decimal 248, hexadecimal F8)
            // and 00111111 (decimal 63, hexadecimal 3F) returns 11000111, which is 
            // 199 in decimal, C7 in hexadecimal.
            Console.WriteLine("Bitwise result: {0}", Convert.ToString(0xf8 ^ 0x3f, 2));
        }
    }
    /*
    Output:
    True
    False
    False
    Bitwise result: 1
    Bitwise result: 0
    Bitwise result: 0
    Bitwise result: 1
    Bitwise result: 110
    Bitwise result: 1010
    Bitwise result: 11000111
    */

이전 예제의 0xf8 ^ 0x3f 계산은 각각 16진수 값 F8과 3F에 해당하는 다음 두 이진 값의 비트 배타적 논리합(Exclusive-OR)을 수행합니다.

1111 1000

0011 1111

배타적 논리합(Exclusive-OR)의 결과는 1100 0111이며, 16진수의 C7에 해당합니다.

참고 항목

참조

C# 연산자

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조

변경 기록

날짜

변경 내용

이유

2010년 12월

코드 예제를 확장했습니다.

고객 의견