In Python, displacement operations and bit operations are common tools for binary-level operations on integers. They are widely used in the fields of underlying programming, algorithm optimization, data compression, encryption, etc. The following is a detailed description of displacement operations and bit operations in Python.
1. Displacement operation
Bit Shift Operations moves the binary representation of an integer to the left or right to the specified number of bits. Python supports two displacement operations: left shift (<<
) and right (>>
)。
1.1 Left shift operation (<<)
- Function: Move the binary bit of the operand to the left by the specified number of bits, and fill the low bit by 0.
- Effect: shifting the n bit left is equivalent to multiplying the operand by 2 n 2^n2n (assuming that it does not overflow).
- grammar:
x << n
(Distance the binary bit of x by n bits left).
Example:
x = 5 # Binary: 0101y = x << 2 # left shift 2 digits: 010100 = 20print(y) # Output: 20
explain:
- 5 = 010 1 2 5 = 0101_25=01012
- Left shift 2 bits: 010 1 2 < < 2 = 01010 0 2 = 2 0 10 0101_2 << 2 = 010100_2 = 20_{10}01012<< 2=0101002=2010
- Equivalent to 5 × 2 2 = 5 × 4 = 20 5 \times 2^2 = 5 \times 4 = 205×22=5×4=20.
1.2 Move right operation (>>)
- Function: Move the binary bit of the operand to the right by the specified number of bits, and fill the sign bits with the high number (for positive number, 0, negative number, 1).
- Effect: Shifting the n bit right is equivalent to dividing the operand by 2 n 2^n2n and rounding downwards.
- grammar:
x >> n
(Transfer the binary bit of x by n bits right).
Example:
x = 20 # Binary: 10100y = x >> 2 # Move right 2 digits: 00101 = 5print(y) # Output: 5 x = -20 # Binary: ...11101100 (complementary code)y = x >> 2 # Move right 2 digits: ...11111011 = -5print(y) # Output: -5
explain:
- For positive number 20 = 10100 0 2 20 = 10100_220=101002, shift right by 2 digits: 1010 0 2 > > 2 = 0010 1 2 = 5 10 10100_2 >> 2 = 00101_2 = 5_{10}101002>>2=001012=510, equivalent to 20 ÷ 2 2 = 20 ÷ 4 = 5 20 \div 2^2 = 20 \div 4 = 520÷22=20÷4=5.
- For negative numbers, keep the sign bits shifted right (supplement 1) to maintain the correctness of negative numbers.
Notes:
- Displacement operations are only applicable to integers, floating point or non-integer types will be thrown.
TypeError
。 - Negative displacement is based on the complement code, and the high position is complemented by 1.
- Too much shift (exceeding integer digits) may result in a result of 0 (positive number shift right) or -1 (negative number shift right).
2. Bit operation
Bitwise Operations is a logical operation bit by bit on the binary bit of an integer. Python supports the following bit operators:
2.1 Bitwise and (&)
- Function: Perform logical and (AND) operations on the binary bits of two numbers bit by bit. Only when the corresponding bits are 1, the result is 1.
- Purpose: mask operation, extract specific bits.
Example:
x = 5 # Binary: 0101y = 3 # Binary: 0011z = x & y # 0101 & 0011 = 0001 print(z) # Output: 1
explain:
- 010 1 2 & 001 1 2 = 000 1 2 = 1 10 0101_2 \& 0011_2 = 0001_2 = 1_{10}01012&00112=00012=110。
2.2 bitwise or (|)
- Function: Perform logical or (OR) operations on the binary bits of two numbers bits, as long as one of the corresponding bits is 1, the result is 1.
- Purpose: Set specific bits and merge flags.
Example:
x = 5 # Binary: 0101y = 3 # Binary: 0011z = x | y # 0101 | 0011 = 0111 print(z) # Output: 7
explain:
- 010 1 2 ∣ 001 1 2 = 011 1 2 = 7 10 0101_2 | 0011_2 = 0111_2 = 7_{10}01012∣00112=01112=710。
2.3 Bitwise XOR (^)
- Function: Perform logical XOR (XOR) operations on the binary bits of two numbers bit by bit. The corresponding bits have different results and the same result is 1, and the same is 0.
- Purpose: flip specific bits, exchange values, and encryption.
Example:
x = 5 # Binary: 0101y = 3 # Binary: 0011z = x ^ y # 0101 ^ 0011 = 0110 print(z) # Output: 6
explain:
- 010 1 2 ∧ 001 1 2 = 011 0 2 = 6 10 0101_2 \wedge 0011_2 = 0110_2 = 6_{10}01012∧00112=01102=610。
The nature of XOR:
- a ∧ a = 0 a \wedge a = 0a∧a=0
- a ∧ 0 = a a \wedge 0 = aa∧0=a
- a ∧ b ∧ b = a a \wedge b \wedge b = aa∧b∧b=a (can be used to exchange values).
2.4 Bitwise inverse (~)
- Function: Inverse the binary bits of the operand bit by bit (0 changes 1, 1 changes 0). The result is the opposite number represented by the complement of the operand (i.e. − x − 1 -x-1−x−1).
- Purpose: invert bits, calculate complement code.
Example:
x = 5 # Binary: 0101y = ~x # Negative: ...11111010 = -6print(y) # Output: -6
explain:
- 5 = 010 1 2 5 = 0101_25=01012, after inversion, it is . . . 111110101 0 2 ...11111010_2...111110102, its value is − 5 − 1 = − 6 -5-1 = -6−5−1=−6.
- Formula: x = − x − 1 ~\text{x} = -\text{x} - 1 x=−x−1.
3. Common application scenarios
Displacement operations and bit operations are very useful in the following scenarios:
3.1 Bit Masking
Use the bitwise and, or, exclusive or operations to check, set or clear a specific bit.
# Check if the nth position is 1def is_bit_set(num: int, n: int) -> bool: return (num & (1 << n)) != 0 print(is_bit_set(5, 0)) # True(5 = 0101, 0th position is 1)print(is_bit_set(5, 1)) # False (No. 1 is 0)
3.2 Permission Management
Use bit operations to represent permission flags.
READ = 1 # 0001 WRITE = 2 # 0010 EXECUTE = 4 # 0100 # Set permissionspermissions = READ | WRITE # 0011 print(permissions) # 3 # Check permissionshas_read = permissions & READ # Check if you have READ permissionsprint(has_read) # 1 (with READ permission)
3.3 Optimized computing
Displacement operations are faster than multiplication and division and are often used to optimize performance.
# Multiply by 4x = 10 y = x << 2 # is equivalent to x * 4print(y) # 40 # Divide by 4z = x >> 2 # is equivalent to x // 4print(z) # 2
3.4 Exchange two variables
Using the ExOR operation allows two integers to be swapped without using temporary variables.
a = 5 b = 3 a ^= b b ^= a a ^= b print(a, b) # 3 5
3.5 bit count
Calculate the number of 1 in the binary representation of a number.
def count_ones(n: int) -> int: count = 0 while n: count += n & 1 # Check the lowest position n >>= 1 # Move right return count print(count_ones(5)) #5 = 0101, output: 2
4. Things to note
- Integer range: Python's integers have no bit limit (unlike C/C++'s 32-bit or 64-bit integers), bit operations and displacement operations can handle any large integer.
- Negative number processing: Negative number is stored in the form of complement code, and when shifting right, the high position is complemented by 1, and when inverse, the result is − x − 1 -x-1−x−1.
- Type limitation: bit operations and displacement operations are only applicable to integers. If you try to use floating point or non-integer type operations, it will be thrown.
TypeError
。 - Performance: Bit operation is usually faster than arithmetic operation, but in Python, performance improvements may not be obvious due to the high-level encapsulation of integer objects (compared to C/C++).
- Readability: The bit operation code may be difficult to understand, and it is recommended to add comments to explain the intention.
5. Comprehensive example
Here is a comprehensive example showing the combination of displacement operations and bit operations:
# Implement a simple bit operation tool classclass BitUtils: @staticmethod def set_bit(num: int, pos: int) -> int: """Set the posth bit to 1""" return num | (1 << pos) @staticmethod def clear_bit(num: int, pos: int) -> int: """Clear posth position (set to 0)""" return num & ~(1 << pos) @staticmethod def toggle_bit(num: int, pos: int) -> int: """Flip the pos position""" return num ^ (1 << pos) @staticmethod def check_bit(num: int, pos: int) -> bool: """Check whether the posth bit is 1""" return (num & (1 << pos)) != 0 # usenum = 5 # Binary: 0101utils = BitUtils() print(utils.set_bit(num, 1)) # Set bit 1: 0101 | 0010 = 0111 = 7print(utils.clear_bit(num, 0)) # Clear 0th bit: 0101 & 1110 = 0100 = 4print(utils.toggle_bit(num, 2)) # Flip the 2nd bit: 0101 ^ 0100 = 0001 = 1print(utils.check_bit(num, 2)) # Check the 2 Bit: True
This is the article about the implementation examples of Python displacement operations and bit operations. For more related contents of Python displacement operations and bit operations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!