繁体   English   中英

Java-按位比较和位移

[英]Java - Bitwise comparisons and shifting of bits

我需要对以下语句进行一些解释,它在做什么?:

int result = 154 + (153 << 8) + (25 << 16) + (64 << 24);
/* what would be the value of result after this line and how it is calculated
Why we need this? */

(153 << 8)等于153 * pow(2, 8)

您实际上是在向左移动位。

另外:-

(153 >> 8)等于153 / pow(2, 8)

您可以猜测为什么。.这实际上是在向右移动位。

EG:-

3 => 0011

3 << 2 is equal to 1100 -> (Which is code for 12)

3 >> 2 is equal to 0000 -> (Which is code for 0) -> you can see - **(3 / 4 = 0)**

注意 :-请注意, right shifting rounds off towards negative infinity

对于EG:-

-3 >> 1 --> -2 (-1.5 is rounded to -2)

让我们看看它是如何发生的:-

用二进制字符串表示:-

-3 ==> 11111111111111111111111111111101

-3 >> 1 ==> 11111111111111111111111111111110 (-3 / 2 = -1.5 -> rounded to -2)

(请注意,最左位由移位前最左端的位填充(在这种情况下为1))

因此,该值变为-2 (对于-3 >> 1,它大于-3 )对于负数会发生这种情况。 Right shifting a negative number gives a number greater than the original number..

这与最左位将被0填充的正数相反。因此, value obtained will be less than the original..

3 ==>  00000000000000000000000000000011

3 >> 1 ==> 00000000000000000000000000000001 (3 / 2 = 1.5 -> rounded to 1)

(因此,最左边的位保持为0。因此,值是1(小于3),即,值朝负无穷大取整,并从1.5变为1)。

同样,您可以设计left-shifting正数和负数的结果。

答案是1075419546。左移位运算符基本上是在十进制数字的二进制表示形式中加上0,因此这将简单地

154 + 153 * 2 ^ 8 + 25 * 2 ^ 16 + 64 * 2 ^ 24

因此,您可以将153转换为其二进制表示形式,然后添加8个零,然后转换回十进制等。

实际上,如果在数学表达式上使用给定的运算符,则其含义如下:

123 << n与123 * 2 ^ n完全相同

例如2 << 2是2 * 2 ^ 2,它是8或与1000相同

否则,您只是向左移动位:

3 = 11,然后3 << 2 = 1100。

希望清楚。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM