Complete the code to set the bit at position 2 in the number.
int number = 8; // binary 1000 int position = 2; int result = number | (1 << [1]); Console.WriteLine(result);
We use position to shift 1 to the correct bit position and then use bitwise OR to set that bit.
Complete the code to clear the bit at position 1 in the number.
int number = 7; // binary 0111 int position = 1; int result = number & ~(1 << [1]); Console.WriteLine(result);
We use position to shift 1 to the correct bit and then invert it with ~ to clear that bit using AND.
Fix the error in toggling the bit at position 0.
int number = 5; // binary 0101 int position = 0; int result = number [1] (1 << position); Console.WriteLine(result);
The XOR operator ^ toggles the bit at the given position.
Fill both blanks to set and then clear the bit at position 3.
int number = 10; // binary 1010 int position = 3; int setBit = number [1] (1 << position); int clearBit = setBit [2] ~(1 << position); Console.WriteLine(clearBit);
Use OR | to set the bit and AND & with inverted mask to clear it.
Fill all three blanks to toggle bit at position 2, then set bit at position 1, then clear bit at position 0.
int number = 6; // binary 0110 int togglePos = 2; int setPos = 1; int clearPos = 0; int step1 = number [1] (1 << togglePos); int step2 = step1 [2] (1 << setPos); int step3 = step2 [3] ~(1 << clearPos); Console.WriteLine(step3);
Toggle uses XOR ^, set uses OR |, and clear uses AND & with inverted mask.
