A SCJP question about right shifts and two´s complement aritmetic
Which of the following expressions results in a positive value in x?(Choose all that apply)
- int x = -1; x = x >>> 5;
- int x = -1; x = x >>> 32;
- byte x = -1; x = x >>> 5;
- int x = -1; x = x >> 5;
To solve this question, we need to know:
- All numerical data types are stored as bit patterns.
- how to represents negative numbers using two´s complement.
- Integers are signed 32 bits values, bytes are 16 bits values.
- All numerical operands returns a integer value.
- >> is a right shift operand (keeps the leftmost bit unchanged), >>> is a unsigned right shift operand (left-bits are zero filled).
- When the value to be shifted (left-operand) is an int, only the last 5 digit bits of the right-hand operand are used to perform the shift. The actual size of the shift is the value of the right-hand operand masked by 31 (0×1f). ie the shift distance is always between 0 and 31 (if right-operand is >= 32, the shift is the right-operand % 32)
With all this by heart, it becomes easy now.
In the first item, we need to use two´s complement to know what is put into the x variable. To represent a negative number, first we invert each bit, then add 1. In this case, 1 = 00000000000000000000000000000001, inverting becomes 11111111111111111111111111111110, then adding 1, 11111111111111111111111111111111.
The operator >>> is a unsigned right shift. In other words, the shift affects all the bit pattern, including the leftmost bit. Doing 5 unsigned shifts in 11111111111111111111111111111111 returns 00000111111111111111111111111111. I´m too lazy to make the aritmetic, but this number is positive for sure (you see the leftmost bit?). The first alternative is part of the answer.
In the second alternative, how the right-operand is equal 32, the shift is 32 % 32 = 0, then the bit pattern stay unchanged, returning a negative value.
The third is easy. Remember: numerical operands returns integers values, always. Then, without a cast, the third item returns a very nasty:
Type mismatch: cannot convert from int to byte
The fourth item shows a signed shift operand, then, doesn´t matter how many shifts, the result is negative.
Conclusion: only the first item returns a positive value.




















January 29th, 2007 at 12:35 am
Hi,
I found your blog via google by accident and have to admit that youve a really interesting blog :-)
Just saved your feed in my reader, have a nice day :)
February 6th, 2007 at 5:31 pm
Thanks, Florian. My posts are sparse, I´m little busy right now, but I promise to post new and interesting material soon.