Python按位运算符
时间:2020-02-23 14:42:27 来源:igfitidea点击:
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.按位与运算符
如果两个位均为1,Python按位运算符将返回1,否则返回0。
>>> 10&7 2 >>>
2.按位或者运算符
如果任意位为1,Python按位或者运算符将返回1。
如果两个位均为0,则它将返回0。
>>> 10|7 15 >>>
3.按位XOR运算符
如果位之一为0,另一位为1,则Python按位XOR运算符返回1。
如果两个位均为0或者1,则返回0。
>>> 10^7 13 >>>
4.按位补码运算符
Python Ones补码数字" A"等于-(A + 1)。
>>> ~10 -11 >>> ~-10 9 >>>
5.按位左移运算符
Python按位左移运算符将右操作数中的给定的次数向左移动左操作数位。
简而言之,二进制数字在末尾附加0。
>>> 10 << 2 40 >>>
6.按位右移运算符
Python的右移运算符与左移运算符完全相反。
然后将左侧操作数位向右侧移动给定的次数。
简单来说,右侧位已删除。
>>> 10 >> 2 2 >>>
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]

