大家好,最近在看《Java编程思想》,在第三章“操作符”中有这么一段:
如果对char、byte或者short类型的数值进行移位处理,那么在移位进行之前,它们会被转成int类型,并且得到的结果也是一个int类型的值。只有数值右端的低5位才有用。这样可防止我们移位超过init型值所具有的位数。(译注:因为2的5次方为32,而int型值只有32位。)
之后google查到了这篇文章:http://blog.csdn.net/showershow/article/details/6959122,不过还是没懂。
虽然译者做了注解,不过我还是不明白,为什么是“只有数值右端的低5位才有用”?有谁能够解释一下吗?谢谢!
PS. 第一次来这里,发现编辑器竟然支持Markdown,非常不错!
When I saw your question, I didn’t understand it either. So I wrote a simple program to see what bytecode is used for the displacement operation:
Use javap to view the compiled bytecode:
I found that ishl is used, and its explanation is like this: http://cs.au.dk/~mis/dOvs/jvmspec/ref-_ishl.html
So I finally understood that the "right-hand side" in the original English text does not refer to the "right end" of a certain value. "right-hand side" is a term that should be translated as "right operand".
This sentence can be understood like this: the displacement operator only uses the lower 5 bits of its right operand.
When I saw this sentence, I understood that only the lower 5 bits of the left operand were used. Maybe you also understood it the same way.
P.S. Turn to wiki: http://en.wikipedia.org/wiki/Bitwise_operation#Shifts_in_Java
The use of "right-hand operand" here more clearly indicates the right-hand operand.
The questioner may have misunderstood.
The specification says Only the lower 5 digits on the right end of the value are useful It means
c
.Let’s look at
b
first. During the calculation process,b
is converted intoint
because theint
type is 32 bits, that is, the value ofb
can be moved up to 31 bits.If b is moved by 33 bits, only the last 5 bits are valid, so:
(For the convenience of testing, the following code is js code)
is equivalent to
That is
For the sake of rigor, the subject tested it in java by himself.
Because int only has 32 bits,
<< 32
overflows. So it is limited to the rightmost 5 digits to prevent overflow (2 ** 5 = 32
).My understanding is this, Java programming philosophy says>>>The value on the right side of this unsigned right shift operator cannot be greater than 31. For example, the right end of the value in
int i = -1,i >>> 33
refers to 33 this value. That is, take the low-order 1 of 33 [0 0001], so only move one bit to the right