📜  Python位运算符

📅  最后修改于: 2022-05-13 01:54:59.652000             🧑  作者: Mango

Python位运算符

运算符用于对值和变量执行操作。这些是执行算术和逻辑计算的特殊符号。运算符操作的值称为操作数。

位运算符

在Python中,按位运算运算符用于对整数执行按位计算。整数首先转换为二进制,然后逐位执行操作,因此得名按位运算运算符。然后以十进制格式返回结果。

注意: Python位运算运算符仅适用于整数。

OPERATORDESCRIPTIONSYNTAX
&Bitwise ANDx & y
|Bitwise ORx | y
~Bitwise NOT~x
^Bitwise XORx ^ y
>>Bitwise right shiftx>>
<<Bitwise left shiftx<<

让我们一一了解每个运算符。
按位与运算符:如果两个位都为 1,则返回 1,否则返回 0。
例子:

a = 10 = 1010 (Binary)
b = 4 =  0100 (Binary)

a & b = 1010
         &
        0100
      = 0000
      = 0 (Decimal)

按位或运算符:如果任一位为 1,则返回 1,否则返回 0。
例子:

a = 10 = 1010 (Binary)
b = 4 =  0100 (Binary)

a | b = 1010
         |
        0100
      = 1110
      = 14 (Decimal)

按位非运算符:返回数字的补码。
例子:

a = 10 = 1010 (Binary)

~a = ~1010
   = -(1010 + 1)
   = -(1011)
   = -11 (Decimal)

按位异或运算符:如果其中一位为 1,另一位为 0,则返回 1,否则返回 false。
例子:

a = 10 = 1010 (Binary)
b = 4 =  0100 (Binary)

a ^ b = 1010
         ^
        0100
      = 1110
      = 14 (Decimal)
Python3
# Python program to show
# bitwise operators
 
a = 10
b = 4
 
# Print bitwise AND operation
print("a & b =", a & b)
 
# Print bitwise OR operation
print("a | b =", a | b)
 
# Print bitwise NOT operation
print("~a =", ~a)
 
# print bitwise XOR operation
print("a ^ b =", a ^ b)


Python3
# Python program to show
# shift operators
 
a = 10
b = -10
 
# print bitwise right shift operator
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)
 
a = 5
b = -10
 
# print bitwise left shift operator
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)


Python3
# Python program to demonstrate
# operator overloading
 
 
class Geek():
    def __init__(self, value):
        self.value = value
 
    def __and__(self, obj):
        print("And operator overloaded")
        if isinstance(obj, Geek):
            return self.value & obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __or__(self, obj):
        print("Or operator overloaded")
        if isinstance(obj, Geek):
            return self.value | obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __xor__(self, obj):
        print("Xor operator overloaded")
        if isinstance(obj, Geek):
            return self.value ^ obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __lshift__(self, obj):
        print("lshift operator overloaded")
        if isinstance(obj, Geek):
            return self.value << obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __rshift__(self, obj):
        print("rshift operator overloaded")
        if isinstance(obj, Geek):
            return self.value & obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __invert__(self):
        print("Invert operator overloaded")
        return ~self.value
 
 
# Driver's code
if __name__ == "__main__":
    a = Geek(10)
    b = Geek(12)
    print(a & b)
    print(a | b)
    print(a ^ b)
    print(a << b)
    print(a >> b)
    print(~a)


输出:

a & b = 0
a | b = 14
~a = -11
a ^ b = 14

移位运算符

这些运算符用于向左或向右移动数字的位,从而分别将数字乘以或除以 2。当我们必须将一个数字乘以或除以 2 时,可以使用它们。
按位右移:将数字的位向右移动并在左侧的空白处填充 0(在负数的情况下填充 1)作为结果。与将数字除以 2 的幂的类似效果。
例子:

Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5

Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5 

按位左移:将数字的位向左移动,结果在空白处填充 0。与将数字乘以 2 的某个幂的效果类似。
例子:

Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20 

Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40 

Python3

# Python program to show
# shift operators
 
a = 10
b = -10
 
# print bitwise right shift operator
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)
 
a = 5
b = -10
 
# print bitwise left shift operator
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)

输出:

a >> 1 = 5
b >> 1 = -5
a << 1 = 10
b << 1 = -20

位运算符重载

运算符重载意味着赋予超出其预定义的操作含义的扩展含义。例如运算符+ 用于添加两个整数以及连接两个字符串和合并两个列表。这是可以实现的,因为 '+'运算符被 int 类和 str 类重载。您可能已经注意到,相同的内置运算符或函数对不同类的对象显示不同的行为,这称为运算符重载
下面是按位运算符重载的简单示例。

Python3

# Python program to demonstrate
# operator overloading
 
 
class Geek():
    def __init__(self, value):
        self.value = value
 
    def __and__(self, obj):
        print("And operator overloaded")
        if isinstance(obj, Geek):
            return self.value & obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __or__(self, obj):
        print("Or operator overloaded")
        if isinstance(obj, Geek):
            return self.value | obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __xor__(self, obj):
        print("Xor operator overloaded")
        if isinstance(obj, Geek):
            return self.value ^ obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __lshift__(self, obj):
        print("lshift operator overloaded")
        if isinstance(obj, Geek):
            return self.value << obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __rshift__(self, obj):
        print("rshift operator overloaded")
        if isinstance(obj, Geek):
            return self.value & obj.value
        else:
            raise ValueError("Must be a object of class Geek")
 
    def __invert__(self):
        print("Invert operator overloaded")
        return ~self.value
 
 
# Driver's code
if __name__ == "__main__":
    a = Geek(10)
    b = Geek(12)
    print(a & b)
    print(a | b)
    print(a ^ b)
    print(a << b)
    print(a >> b)
    print(~a)

输出:

And operator overloaded
8
Or operator overloaded
14
Xor operator overloaded
8
lshift operator overloaded
40960
rshift operator overloaded
8
Invert operator overloaded
-11

注意:要了解有关运算符重载的更多信息,请单击此处。