Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Shift Operator and auto promotion

Tags:

java

bit-shift

I'm a newbie Java programmer, who is reading Thinking In Java by Bruce Eckel.

In the 5th chapter, operators have been discussed. Where it is talking about shift operators (<<, >>, >>>) he says:

If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you’re operating on a long, you’ll get a long result. Only the six low-order bits of the right-hand side will be used, so you can’t shift more than the number of bits in a long.

Which I can't understand the meaning. Specially the bold sentences. Could you clarify it a bit?

like image 291
mrdaliri Avatar asked Jan 08 '23 10:01

mrdaliri


1 Answers

I feel that the other answers are a bit incomplete.

It's true that an int is 32 bits, and the language doesn't let you shift more than 32 bits. What's gotten left out is that if you tell it to shift more than 32 bits, the shift amount will be taken modulo 32. That is, if x is an int, x >> 32 is the same as x >> 0 (i.e. just x), x >> 33 is the same as x >> 1, x >> 66 is the same as x >> 2, etc. Using only the low-order 5 bits of the right argument is the same as taking the argument modulo 32 (using the mathematical definition, so that -1 mod 32 == 31, -2 mod 32 == 30, etc.).

Similarly, long is 64 bits, which means that the right argument is computed modulo 64, which is the same as using only the low-order 6 bits of the right argument.

Why Java did it this way, I don't know. In my opinion, it would be more consistent if it simply let you shift by a large amount, shifting all the bits out of the integer and resulting in 0 (except that >> sign-extends, so the result would be 0 or -1). It would be consistent mathematically, because for positive x and y, x >> y would always be equal to x / (2^y) truncated down to an integer, even if y >= 32. Java's way of handling shift amounts that are >= 32 or >= 64 isn't useful in any way I can see.

like image 164
ajb Avatar answered Jan 10 '23 23:01

ajb