关于java中的移位,例如
int a=-8;
System.out.println(a>>>33);//2147483644
System.out.println(a>>>1); //2147483644
这里我采用了逻辑右移(无符号右移)为例,对-8进行逻辑右移,移动33位和移动1位的效果是一样的,其原因是移动33位时对其进行取模操作(与32相除的余数),对其余数进行移位,请问Java中这样设计的理由是什么?为什么不是当逻辑右移超过32位时,其结果应该为0,这样不是更符合常理吗?
巴扎黑2017-04-17 17:42:08
I saw someone questioned my answer, so I changed it
What the poster said is why shift 33 is not set to 0 directly?
Because if you operate in this way, first of all, there will be a lot of magic numbers in the simple code ~ Because if I shift 33, it can also be 0, and if I shift 34, it can also be 0...
In this way, there is no standard. Then the shift operation must be performed step by step (save the value, then calculate, and so on). This kind of unlimited movement must be unacceptable to computers and language designers! ! ! !
*The shift operation is simply the underlying multiplication by 2 and division by 2. First of all, I want to say point of view! No non-zero number divided by 2^n will get 0. People who know a little bit about mathematics should easily be able to figure out why they get the result 0 when 1 >> 1? ? ? Because bit operations only work on integers, this is the same concept as directly using 1/2 as 0 instead of 0.5.
大家讲道理2017-04-17 17:42:08
Due to its high efficiency, the shift operation is often used to optimize the */
method. Shifting one position to the left is equivalent to *2
, and shifting one position to the right Equivalent to /2
. Of course, this is within a certain range of conditions. */
法,向左移一位相当于*2
,向右移一位相当于/2
。当然,这是在一定范围条件内的。
至于>>>
33位这样的不合理
的移位,取模操作后才去进行移位,是一种可选方案吧?应该另有它用,比如在进行一些特殊算法(如MD5
As for >>>
33 bits of unreasonable
shifting, it is optional to perform the shift after taking the modulo operation. Plan? There should be other uses, such as performing some special algorithms (such as MD5
encryption algorithm). As for what the first floor explained, I cannot agree with it. Shifting and multiplication and division are equivalent.
PHP中文网2017-04-17 17:42:08
You shifted once past the maximum length of the type to get 0, why not just set it to 0?