Bit manipulation on #加密圆桌讨论 is an operation performed on binary digits and is commonly used in programming and low-level development. Here are some common techniques:
Bitwise AND (&)
• Purpose: Can be used to get the value of a specific bit. For example, to check if the least significant bit of a number is 1, you can perform a bitwise AND operation with the number and 1 (num & 1).
• Example: 5 (binary 101) & 1 (binary 001) = 1, indicating that the least significant bit is 1.
Bitwise OR (|)
• Purpose: Can set a specific bit to 1. For instance, to set the 3rd bit of a number to 1, you can perform a bitwise OR operation with the number and (1 << 3).
• Example: num = 5 (101), num | (1 << 2) = 5 | 4 (100) = 9 (1001), the 3rd bit (counting from 0) is set to 1.
Bitwise XOR (^)
• Purpose: Can swap two numbers without using a temporary variable and can also flip a specific bit.
• Example: To swap a and b, a = a ^ b, b = b ^ a, a = a ^ b; to flip the 1st bit of num, num ^= (1 << 1).
Left Shift (<<)
• Purpose: Equivalent to multiplying by 2 raised to the power of n (where n is the number of left shifts), and is more efficient than multiplication.
• Example: 3 << 2 = 3 * 2² = 12.
Right Shift (>>)
• Purpose: Equivalent to dividing by 2 raised to the power of n and rounding down, also more efficient than division.
• Example: 13 >> 2 = 13 / 2² = 3 (rounded down).
Bitwise NOT (~)
• Purpose: Flips all binary bits of a number, the result is -(num + 1).
• Example: ~5 = -6, because the binary of 5 is 00000101, flipping it gives 11111010, which is the two's complement of -6.
Determine Odd or Even
• Method: Use num & 1; a result of 1 indicates an odd number, while a result of 0 indicates an even number.
• Example: 7 & 1 = 1 (odd), 8 & 1 = 0 (even).
Clear the Lowest Set Bit
• Method: num & (num - 1), can be used to count the number of 1s in binary, etc.
• Example: 6 (110) & 5 (101) = 4 (100), clearing the lowest set bit.