简体   繁体   English

<<= 或 >>= 在 Java 中是什么意思?

[英]What does <<= or >>= mean in Java?

I was learning about assignment operators in Java in W3schools.我在 W3schools 的 Java 中学习赋值运算符。 But I didn't get what these two operators mean?但是我没明白这两个运营商是什么意思?

These are examples of assignment operators .这些是赋值运算符的示例。 Essentially, they both perform the arithmetic operation on a variable, and assign its result to that variable, in a single operation.本质上,它们都对变量执行算术运算,并将其结果分配给该变量,在单个操作中。 They're equivalent to doing it in two steps, for the most part:在大多数情况下,它们相当于分两步完成:

int a = 23;
int b = 2;

a += b; // addition - same as `a = a + b`
a -= b; // subtraction
a *= b; // multiplication
a /= b; // floor division
a %= b; // modulo division
a &= b; // bitwise and
a |= b; // bitwise or
a ^= b; // bitwise xor
a >>= b; // right bitshift
a <<= b; // left bitshift

The bitshift operations in particular are the ones you're asking about.特别是位移操作是您要询问的操作。 They take the binary representation of a number, and shift it left or right by the given number of places, filling in missing spaces with zeroes.他们采用数字的二进制表示,并将其向左或向右移动给定的位数,用零填充缺失的空格。 For example, the binary representation of 23 is 00010111 .例如,23 的二进制表示是00010111

So, 23 << 2 would be equal to 01011100 , or 92;因此, 23 << 2将等于01011100或 92; whereas 23 >> 2 would be equal to 00000101 , or 5.23 >> 2将等于00000101或 5。

You could also think of it as doing integer multiplication or division using powers of two:您也可以将其视为使用 2 的幂进行 integer 乘法或除法:

  • a << b will generally produce the same result as a * Math.pow(2, b) a << b通常会产生与a * Math.pow(2, b)相同的结果
  • a >> b will generally produce the same result as a / Math.pow(2, b) a >> b通常会产生与a / Math.pow(2, b)相同的结果

it's short expression, just like i = i >> 2 and i = i << 2这是一个简短的表达式,就像i = i >> 2i = i << 2

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

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