Bitwise and Bit Shift Operators in Java - Quiz
Total: 6 questions
1. What is the difference between >> and >>>?
What is the difference between >> and >>>?
>> is the arithmetic right shift: the sign bit is copied in from the left, so the sign of the number is preserved (negatives get 1s added). >>> is the unsigned (logical) right shift: zeros are always added on the left, which turns a negative number into a large positive one. For non-negative numbers both operators give the same result. Java has no <<< operator. Example: -8 >> 1 is -4, while -8 >>> 1 is 2147483644.
2. Why is ~x always equal to -x - 1?
Why is ~x always equal to -x - 1?
Integers in Java are stored in two's complement. The ~ operator flips every bit. In two's complement, negation is done as "flip the bits and add one": -x = ~x + 1. Rearranging gives ~x = -x - 1. For example: ~5 = -6, ~0 = -1, ~(-1) = 0.
3. What is a bit mask, and how does it work with the & operator?
What is a bit mask, and how does it work with the & operator?
A mask is a number whose set bits mark the positions you care about. The expression value & mask clears every bit except the ones under the 1s of the mask, which is how you extract specific bits or test flags. For example, value & 0xFF keeps only the lowest byte, and flags & READ tells you whether a particular flag is set (a non-zero result means it is). The mask variable is conventionally named mask.
4. How can you check whether a number is odd or even without the % operator?
How can you check whether a number is odd or even without the % operator?
Use x & 1. The lowest bit is 1 for odd numbers and 0 for even ones, so (x & 1) == 0 means the number is even and (x & 1) == 1 means it is odd. This trick also works correctly for negative numbers (unlike x % 2, which can return -1 for negatives) and is usually faster than division.
5. What happens to byte and short values in bitwise operations?
What happens to byte and short values in bitwise operations?
Before the operation runs, byte and short operands are automatically promoted to int. As a result, the outcome of &, |, ^ and the shifts is of type int, and you cannot assign it back to a byte/short without an explicit cast. For example, byte b = 10; b << 28 is computed as an int and produces a value that no longer fits in a byte.
6. How do multiplication and division by a power of two map to shift operators?
How do multiplication and division by a power of two map to shift operators?
A left shift by n bits multiplies by 2 to the power n: x << 1 is x*2, x << 3 is x*8. A right shift >> by n bits divides by 2 to the power n, rounding down: x >> 1 is x/2. Watch out: << can overflow (high bits fall off the end of the int), and for negative numbers >> rounds toward negative infinity rather than toward zero the way / does.