웹사이트 검색

파이썬 비트 연산자


Python 비트 연산자는 정수에 대한 비트 계산을 수행하는 데 사용됩니다. 정수는 이진 형식으로 변환된 다음 비트 단위로 연산이 수행되므로 비트 연산자라고 합니다. Python 비트 연산자는 정수에서만 작동하며 최종 출력은 10진수 형식으로 반환됩니다. Python 비트 연산자는 이진 연산자라고도 합니다.

파이썬 비트 연산자

파이썬에는 6개의 비트 연산자가 있습니다. 아래 표는 이에 대한 간략한 세부 정보를 제공합니다.

Bitwise Operator Description Simple Example
& Bitwise AND Operator 10 & 7 = 2
Bitwise OR Operator
^ Bitwise XOR Operator 10 ^ 7 = 13
~ Bitwise Ones’ Compliment Operator ~10 = -11
<< Bitwise Left Shift operator 10<<2 = 40
>> Bitwise Right Shift Operator 10>>1 = 5

이러한 연산자를 하나씩 살펴보고 어떻게 작동하는지 이해해 봅시다.

1. 비트 AND 연산자

Python 비트 및 연산자는 두 비트가 모두 1이면 1을 반환하고 그렇지 않으면 0을 반환합니다.

>>> 10&7
2
>>> 

2. 비트 OR 연산자

Python bitwise or 연산자는 비트 중 하나라도 1이면 1을 반환합니다. 두 비트가 모두 0이면 0을 반환합니다.

>>> 10|7
15
>>> 

3. 비트별 XOR 연산자

Python 비트 XOR 연산자는 비트 중 하나가 0이고 다른 비트가 1이면 1을 반환합니다. 두 비트가 모두 0 또는 1이면 0을 반환합니다.

>>> 10^7
13
>>> 

4. Bitwise Ones의 보수 연산자

Python Ones의 숫자 'A'의 보수는 -(A+1)과 같습니다.

>>> ~10
-11
>>> ~-10
9
>>> 

5. 비트 왼쪽 시프트 연산자

파이썬 비트 왼쪽 시프트 연산자는 왼쪽 피연산자 비트를 오른쪽 피연산자에서 주어진 횟수만큼 왼쪽으로 이동합니다. 간단히 말해서 이진수는 끝에 0이 추가됩니다.

>>> 10 << 2
40
>>> 

6. 비트 오른쪽 시프트 연산자

파이썬 오른쪽 시프트 연산자는 왼쪽 시프트 연산자와 정반대입니다. 그런 다음 왼쪽 피연산자 비트가 주어진 횟수만큼 오른쪽으로 이동합니다. 간단히 말해서 오른쪽 비트가 제거됩니다.

>>> 10 >> 2
2
>>>  

Python 비트 연산자 오버로딩

파이썬은 연산자 오버로딩을 지원합니다. 사용자 지정 개체에 대한 비트 연산자를 지원하기 위해 구현할 수 있는 다양한 메서드가 있습니다.

Bitwise Operator Method to Implement
& __and__(self, other)
^ __xor__(self, other)
~ __invert__(self)
<< __lshift__(self, other)
>> __rshift__(self, other)

다음은 사용자 지정 개체에 대한 비트 연산자 오버로딩의 예입니다.

class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __and__(self, other):
        print('Bitwise AND operator overloaded')
        if isinstance(other, Data):
            return Data(self.id & other.id)
        else:
            raise ValueError('Argument must be object of Data')

    def __or__(self, other):
        print('Bitwise OR operator overloaded')
        if isinstance(other, Data):
            return Data(self.id | other.id)
        else:
            raise ValueError('Argument must be object of Data')

    def __xor__(self, other):
        print('Bitwise XOR operator overloaded')
        if isinstance(other, Data):
            return Data(self.id ^ other.id)
        else:
            raise ValueError('Argument must be object of Data')

    def __lshift__(self, other):
        print('Bitwise Left Shift operator overloaded')
        if isinstance(other, int):
            return Data(self.id << other)
        else:
            raise ValueError('Argument must be integer')

    def __rshift__(self, other):
        print('Bitwise Right Shift operator overloaded')
        if isinstance(other, int):
            return Data(self.id >> other)
        else:
            raise ValueError('Argument must be integer')

    def __invert__(self):
        print('Bitwise Ones Complement operator overloaded')
        return Data(~self.id)

    def __str__(self):
        return f'Data[{self.id}]'


d1 = Data(10)
d2 = Data(7)

print(f'd1&d2 = {d1&d2}')
print(f'd1|d2 = {d1|d2}')
print(f'd1^d2 = {d1^d2}')
print(f'd1<<2 = {d1<<2}')
print(f'd1>>2 = {d1>>2}')
print(f'~d1 = {~d1}')

산출:

Bitwise AND operator overloaded
d1&d2 = Data[2]
Bitwise OR operator overloaded
d1|d2 = Data[15]
Bitwise XOR operator overloaded
d1^d2 = Data[13]
Bitwise Left Shift operator overloaded
d1<<2 = Data[40]
Bitwise Right Shift operator overloaded
d1>>2 = Data[2]
Bitwise Ones Complement operator overloaded
~d1 = Data[-11]

새로운 문자열 형식에 익숙하지 않은 경우 Python에서 f-문자열을 읽어보십시오.

요약

Python 비트 연산자는 주로 수학 계산에 사용됩니다. 사용자 지정 클래스 구현을 위한 비트 연산자를 지원하는 특정 메서드를 구현할 수도 있습니다.