$ETH Bit operations are operations performed on binary bits and are 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 certain bit. For example, to check if the least significant bit of a number is 1, use the 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 certain bit to 1. For example, to set the 3rd bit of a number to 1, use the 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 negate a certain bit.

• Example: To swap a and b, a = a ^ b, b = b ^ a, a = a ^ b; to negate 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: Negates all binary bits of a number, and the result is -(num + 1).

• Example: ~5 = -6, because the binary of 5 is 00000101, after negation it becomes 11111010, which is the two's complement of -6.

Odd or Even Check

• Method: Use num & 1, result is 1 for odd, and 0 for even.

• 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), the lowest set bit is cleared.