Python 位运算符

Python 位运算符用于对整数执行位运算。整数被转换为二进制格式,然后逐位执行运算,因此得名位运算符。Python 位运算符仅适用于整数,最终输出以十进制格式返回。Python 位运算符也称为二进制运算符。

Python 位运算符

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. 位与运算符

Python 位与运算符在两个位都为1时返回1,否则返回0。

>>> 10&7
2
>>> 
Python Bitwise And Operator

2. 位或运算符

Python 位或运算符在任一位为1时返回1。如果两个位都为0,则返回0。

>>> 10|7
15
>>> 
Python Bitwise Or Operator

3. 位异或运算符

Python 位异或运算符在其中一个位为0,另一个位为1时返回1。如果两个位都为0或者1,则返回0。

>>> 10^7
13
>>> 
Python Bitwise XOR Operator

4. 位取反运算符

数‘A’的Python位取反等于-(A+1)。

>>> ~10
-11
>>> ~-10
9
>>> 
Python Bitwise Ones Complement Operator

5. 位左移运算符

Python 位左移运算符将左操作数的位向左移动给定次数,由右操作数指定。简单来说,二进制数在末尾添加0。

>>> 10 << 2
40
>>> 
Python Bitwise Left Shift Operator

6. 位右移运算符

Python的右移操作符正好是左移操作符的相反。然后左侧操作数的位向右移动给定次数。简单来说,右侧的位将被移除。

>>> 10 >> 2
2
>>>  
Python Bitwise Right Shift Operator

Python位运算符重载

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-strings

摘要

Python位运算符主要用于数学计算。我们也可以实现特定的方法来支持自定义类实现的位运算符。

Source:
https://www.digitalocean.com/community/tutorials/python-bitwise-operators