简体   繁体   English

在java中移位时的不同行为

[英]Differing behaviour when shifting bits in java

I'm working with bit shifting in Java and have the following piece of code that works as expected: 我正在使用Java中的位移,并使下面的代码按预期工作:

final byte value = 1;
final int shift = 1;
byte result = value << shift;

This produces the value 2 as expected. 这会产生预期的值2 If however I attempt to extract this into a method like so: 但是,如果我尝试将其提取到如下方法中:

private void shiftAndCheck(final byte value, final int shift) {
  byte result = value << shift;
}

This results in a compilation error: 这会导致编译错误:

java: incompatible types: possible lossy conversion from int to byte

The question is what is it about the method that causes this to fail? 问题是导致失败的方法是什么?

Since the value and shift are compile-time constants in this snippet: 由于valueshift是此代码段中的编译时常量:

final byte value = 1;
final int shift = 1;
byte result = value << shift;

then the compiler inlines their values (replaces all the occurrences of value and shift with their actual values of 1 ) and can verify before Runtime that the result of value << shift won't cause any loss of precision. 然后编译器内联它们的值(替换所有出现的value并使用它们的实际值1 shift )并且可以在运行时之前验证value << shift的结果不会导致任何精度损失。


Meanwhile, for the second snippet: 同时,对于第二个片段:

private void shiftAndCheck(final byte value, final int shift) {
  byte result = value << shift;
}

the compiler has no evidence that shift will represent such value, which wouldn't cause loss of precision and that's why raises a compilation error. 编译器没有证据表明shift代表这样的值,这不会导致精度损失,这就是为什么会引发编译错误。

If compilation was possible in this case, then you'd have been able to do shiftAndCheck(1, 32); 如果在这种情况下可以编译,那么你就可以做shiftAndCheck(1, 32); which would result in overflowing the byte type. 这会导致byte类型溢出。

默认情况下,对非浮点数的算术运算会产生一个int结果

    private void shiftAndCheck(final byte value, final int shift) {
        byte result = (byte) (value << shift);
    }

As @Konstantin already said it returns int , so either cast it into byte or use int result . 由于@Konstantin已经说它返回int ,所以要么将其转换为byte,要么使用int result

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

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