[英]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.