Challenge your grasp of bitwise operators with these medium-level questions designed to deepen your understanding of binary manipulation, masking, shifting, and real-world applications. Strengthen your skills in bitwise logic and discover practical scenarios where these operators are essential.
What is the result of applying the bitwise AND operator to the binary numbers 1101 and 1011?
Explanation: The bitwise AND operator compares each bit of the two numbers and returns 1 only when both bits are 1. For 1101 AND 1011, only the first and last positions are both 1, resulting in 1001. Option 1100 is incorrect because it sets the third bit erroneously; 1111 would suggest all bits are 1, which is not the case; 1000 only has the first bit set and misses the last. Thus, 1001 is correct.
If you use the bitwise OR operator to set a specific bit in a byte, which effect does it have on the targeted bit?
Explanation: Using the bitwise OR with a mask sets the chosen bit to 1 no matter what the original value was. Flipping its value is the behavior of XOR, not OR. Forcing to 0 is done using bitwise AND with the complement of the mask. Leaving all bits unchanged ignores the targeted operation. Therefore, 'Forces it to 1, regardless of the original value' is correct.
Which number do you get if you perform a left bitwise shift (u003Cu003C) by 2 positions on the number 5 (0101 in binary)?
Explanation: Shifting bits to the left by 2 positions multiplies the number by 4, so 5 becomes 20 (binary 10100). Choosing 10 or 12 would correspond to incorrect values for a two-place left shift or perhaps confusion with addition. The value 15 results from binary 1111, not shifting 5 to the left. Therefore, 20 is the correct answer.
How can you check if the third bit (from the right, zero-indexed) is set to 1 in an integer value using bitwise operations?
Explanation: Applying bitwise AND with a mask matching the third bit (0b100) allows you to isolate and check that bit. OR would set the bit, not check it. XOR would only check if the value was different, not directly whether the bit is set. Shifting by three would not isolate the third bit correctly. Therefore, AND with 0b100 and comparing to zero is correct.
In programming, how can the bitwise XOR operator be used to swap two integer variables x and y without a temporary variable?
Explanation: The XOR swap algorithm uses the property that XOR-ing a value with itself results in zero and with zero leaves the value unchanged, enabling value swapping without a temporary variable. Using AND and OR cannot swap values correctly. Addition and subtraction is a different approach, not XOR-based, and shifting does not perform swapping. Hence, the first option is correct.