int number = 8; // binary 1000 int position = 1; int result = number | (1 << position); Console.WriteLine(result);
The original number is 8 (binary 1000). Setting bit at position 1 (counting from 0) means turning the second bit from right to 1. 1 << 1 is 2 (binary 0010). OR operation 1000 | 0010 = 1010 which is 10 in decimal.
int number = 15; // binary 1111 int position = 3; int result = number & ~(1 << position); Console.WriteLine(result);
Number 15 is 1111 in binary. Clearing bit at position 3 (the leftmost bit) means turning that bit to 0. 1 << 3 is 8 (1000). Negation is 0111 (7). AND operation 1111 & 0111 = 0111 which is 7 in decimal.
int number = 5; // binary 0101 int position = 2; int result = number ^ (1 << position); Console.WriteLine(result);
Number 5 is 0101 in binary. Toggling bit at position 2 (third bit from right) flips it. 1 << 2 is 4 (0100). XOR 0101 ^ 0100 = 0001 which is 1 in decimal. But careful: position 2 bit is currently 1, toggling flips it to 0, so result is 1.
int number = 2; // binary 0010 int position = 0; int result = number ^ (1 << position); result = result ^ (1 << position); Console.WriteLine(result);
Number 2 is 0010. Toggling bit 0 flips the last bit: 0010 ^ 0001 = 0011 (3). Toggling again flips it back: 0011 ^ 0001 = 0010 (2). So the final result is 2.
To clear a bit, we AND the number with the negation of the bit mask at position k. This sets that bit to 0 and leaves others unchanged. Option B does this correctly.
