Java中的左移0

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18006807/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:44:15  来源:igfitidea点击:

Left bit shift 0 in Java

javabitwise-operatorsbit-shift

提问by Riz

Consider:

考虑:

   int a = 0;
   a |= 1 << a;
   System.out.println(a); 

It prints "1". Why? I thought left bit shifting 0 by any number of times was still 0. Where's it pulling the 1 from?

它打印“1”。为什么?我认为将 0 左移任意次数仍然是 0。它从哪里拉出 1?

采纳答案by Mike Christensen

The expression 1 << a;will shift the value 1, anumber of times.

该表达式1 << a;将移动值1a次数。

In other words, you have the value 1:

换句话说,您的值为 1:

0000001

Now, you shift the whole thing over 0 bits to the left. You then have:

现在,您将整个内容向左移动 0 位。然后你有:

0000001

You then have:

然后你有:

a |= 1 << a;

Which resolves to:

其解析为:

a = 0000000 | 0000001

Or:

或者:

a = 1;

You might have the operands mixed up. If you're trying to shift the value 0 one bit to the left, you'd want:

您可能混淆了操作数。如果您试图将值 0 向左移动一位,您需要:

a |= a << 1;

回答by nashuald

You are using the operator << in a wrong way. It must to be:

您以错误的方式使用运算符 << 。它必须是:

int a = 0;
a |= a << 1;
System.out.println(a);

回答by William Morrison

You are left shifting the literal 1by the variable a. The value of variable ais zero. 1<<0 = 1

您将文字左移1变量a。变量的值a为零。1<<0 = 1

So you've just got your variables flipped. Try reversing the variables.

所以你刚刚改变了你的变量。尝试反转变量。