i'm newbie java programmer, reading thinking in java bruce eckel.
in 5th chapter, operators have been discussed. talking shift operators (<<, >>, >>>) says:
if shift char, byte, or short, promoted int before shift takes place, , result int. only 5 low-order bits of right-hand side used. prevents shifting more number of bits in int. if you’re operating on long, you’ll long result. only 6 low-order bits of right-hand side used, can’t shift more number of bits in long.
which can't understand meaning. specially bold sentences. clarify bit?
i feel other answers bit incomplete.
it's true int
32 bits, , language doesn't let shift more 32 bits. what's gotten left out if tell shift more 32 bits, shift amount taken modulo 32. is, if x
int
, x >> 32
same x >> 0
(i.e. x
), x >> 33
same x >> 1
, x >> 66
same x >> 2
, etc. using low-order 5 bits of right argument same taking argument modulo 32 (using mathematical definition, -1 mod 32 == 31, -2 mod 32 == 30, etc.).
similarly, long
64 bits, means right argument computed modulo 64, same using low-order 6 bits of right argument.
why java did way, don't know. in opinion, more consistent if let shift large amount, shifting bits out of integer , resulting in 0 (except >>
sign-extends, result 0 or -1). consistent mathematically, because positive x
, y
, x >> y
equal x / (2^y)
truncated down integer, if y
>= 32. java's way of handling shift amounts >= 32 or >= 64 isn't useful in way can see.
Comments
Post a Comment