python bitwise operator case

When we need to perform bitwise operations on binary numbers, Python provides bitwise operators to handle. Here are some common bitwise operators and cases:

1. Bitwise AND (&): Performs a logical AND operation on each bit of the two operands and returns the result.

a = 5  # 二进制表示为 0101
b = 3  # 二进制表示为 0011

result = a & b  # 二进制结果为 0001,转换为十进制为 1
print(result)  # 输出: 1

2. Bitwise OR (|): Performs a logical OR operation on each bit of the two operands and returns the result.

a = 5  # 二进制表示为 0101
b = 3  # 二进制表示为 0011

result = a | b  # 二进制结果为 0111,转换为十进制为 7
print(result)  # 输出: 7

3. Bitwise XOR (^): Performs a logical XOR operation on each bit of the two operands and returns the result.

a = 5  # 二进制表示为 0101
b = 3  # 二进制表示为 0011

result = a ^ b  # 二进制结果为 0110,转换为十进制为 6
print(result)  # 输出: 6

4. Bitwise inversion (~): Performs a logical inversion operation on each bit of the operand and returns the result.

Now we can understand the above example, 11110110 is obtained after the bitwise inversion of 9, the first bit is 1, and the source code is a negative value.
After inversion, it is 00001001, plus 1 to get 00001010, its value is 10, plus a minus sign is -10.

immediately  ~9=-10

a = 5  # 二进制表示为 0101

result = ~a  # 二进制结果为 1010(在计算机中使用补码表示负数)
print(result)  # 输出: -6

5. Left shift (<<): Shift each bit of the operand to the left by the specified number of bits and return the result.

a = 5  # 二进制表示为 0101

result = a << 2  # 二进制结果为 010100(在计算机中使用补码表示负数)
print(result)  # 输出: 20

6. Right shift (>>): Shift each bit of the operand to the right by the specified number of bits and return the result.

a = 5  # 二进制表示为 0101

result = a >> 1  # 二进制结果为 0010
print(result)  # 输出: 2

These are some common bitwise operators and cases that are very useful when working with binary numbers. Note that in practice, bitwise operators may have more complex uses.

Now we can understand the above example, 11110110 is obtained after the bitwise inversion of 9, the first bit is 1, and the source code is a negative value.
After inversion, it is 00001001, plus 1 to get 00001010, its value is 10, plus a minus sign is -10.

immediately  ~9=-10

Guess you like

Origin blog.csdn.net/m0_74972727/article/details/131471959